我有下表,我希望根据每个 CONTRACT_ID 可用的 TYPE 的数量获得结果。
表格
______________________________________________________________________________________
|Source | CONTRACT_ID | TYPE | ADDRESS | PHONE |
______________________________________________________________________________________
|Source1 | 1234 | INSURED | unique1 | 4321 |
______________________________________________________________________________________
|Source1 | 1234 | INSURED | unique1 | 4321 |
______________________________________________________________________________________
|Source1 | 1234 | DRIVER | unique1 | 4321 |
______________________________________________________________________________________
|Source1 | 1234 | INSURED | unique1 | 4321 |
______________________________________________________________________________________
|Source2 | 2345 | INSURED | unique2 | 5678 |
______________________________________________________________________________________
|Source2 | 2345 | DRIVER | unique2 | 5678 |
______________________________________________________________________________________
|Source2 | 2345 | CONTRACT | unique2 | 5678 |
______________________________________________________________________________________
结果:
______________________________________________________________________________________
|Source | CONTRACT_ID | ROLES | ADDRESS | PHONE |
______________________________________________________________________________________
|Source1 | 1234 | 2 | unique1 | 4321 |
______________________________________________________________________________________
|Source2 | 2345 | 3 | unique2 | 5678 |
______________________________________________________________________________________
,结果表中的 ROLES 列应为不同 CONTRACT_ID 的不同 TYPE 的数量。
有人可以帮忙吗?
答案 0 :(得分:1)
SELECT max(source) , contract_id ,
count( DISTINCT type) roles , max(address), max(phone)
FROM Table group by contract_id ;
答案 1 :(得分:0)
我认为您正在寻找count(distinct)
:
select Source, CONTRACT_ID, ADDRESS, PHONE, count(distinct type) as roles
from t
group by Source, CONTRACT_ID, ADDRESS, PHONE ;
这不是"过滤"。它是"聚合"。