我有一個TableA的表結構,如:
-------------------
Id | Type
-------------------
12345 | RegA
12345 | RegB
23456 | RegB
45678 | RegB
45678 | RegA
-------------------
我想獲得多少個ID有多少個型別。在上述情況下,1 個ID具有 1 個不同的Type,而 2 個ID每個具有 2 個不同的Type。因此,輸出應如下所示:
---------------------------
Id_Count | Type_Count
---------------------------
2 | 2
1 | 1
---------------------------
我可以通過如下所示的個人ID接收計數。但不能像上面提到的那樣檢索。
-------------------------------
Id_Count | Type_Count
-------------------------------
12345 | 2
45678 | 2
23456 | 1
-------------------------------
uj5u.com熱心網友回復:
您可以使用 count(dictinct type) 作為外部計數的結果
select count(*), type_count
from (
select id , count(distinct Type) type_count
from my_table
group by id ) t
group by type_count
uj5u.com熱心網友回復:
您可以通過對第一個結果(在子查詢中)使用第二個聚合來實作這一點,例如
SELECT
COUNT(1) as Id_Count,
Type_Count
FROM (
SELECT
Id,
COUNT(1) as Type_Count
FROM
TableA
GROUP BY
Id
) t
GROUP BY Type_Count
編輯 1:正如@mathguy 在評論中強調的那樣,如果您的真實資料集中有重復的條目,以下修改使用COUNT(DISTINCT type)將計算type每個組中的每次出現僅一次,類似地 for idinCOUNT(DISTINCT id)可能更合適
SELECT
COUNT(DISTINCT Id) as Id_Count,
Type_Count
FROM (
SELECT
Id,
COUNT(DISTINCT Type) as Type_Count
FROM
TableA
GROUP BY
Id
) t
GROUP BY Type_Count
uj5u.com熱心網友回復:
嘗試這個 :
SELECT
Id AS Id_Count,
COUNT(*) as Type_Count
FROM
my_table
GROUP BY
type
ORDER BY
Type_Count ASC
uj5u.com熱心網友回復:
如果您可以選擇使用 window function
select distinct
count(id) over (partition by count(distinct type)) as id_count,
count(distinct type) as type_count
from t
group by id;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/373080.html
上一篇:使用只有特定列的日期列創建表
下一篇:如何避免與case陳述句重復
