如果我有以下样本数据:
╔══════════════╦══════════════════╦════════════╦═══════╗
║ Client ║ con_id ║ mat1_07_03 ║ Ccode ║
╠══════════════╬══════════════════╬════════════╬═══════╣
║ Clients Name ║ C13109BBFD511534 ║ $1,062.00 ║ NOFL ║
║ Clients Name ║ C11AC9BBF74D6882 ║ $879.73 ║ NOFL ║
║ Clients Name ║ C12A69BBF1ACB578 ║ $2,790.29 ║ NOFA ║
║ Clients Name ║ C12A69BBF1ACB578 ║ $912.00 ║ NOFL ║
║ Clients Name ║ C6B0CA1A767C9744 ║ $2,180.11 ║ NOFL ║
║ Clients Name ║ C11AC9BBF74D6882 ║ $878.67 ║ NOFA ║
║ Clients Name ║ C13B79BBF4F1F450 ║ $300.00 ║ NOFL ║
║ Clients Name ║ C12A69BBF1ACB578 ║ $1,790.67 ║ NOFL ║
║ Clients Name ║ CA6869E2FE38A449 ║ $240.00 ║ NOFA ║
║ Clients Name ║ C46439FB0D847140 ║ $3,392.66 ║ NOFL ║
║ Clients Name ║ C12A69BBF1ACB578 ║ $1,791.73 ║ NOFA ║
║ Clients Name ║ C13B49BBF12ED236 ║ $0.00 ║ NOFL ║
║ Clients Name ║ C12A69BBF1ACB578 ║ $879.73 ║ NOFL ║
╚══════════════╩══════════════════╩════════════╩═══════╝
并应用以下查询:
SELECT
[Client]=MAX(m.Client)
,[CaseCount]=COUNT(m.con_id)
,[AmtInDispute]=CONVERT(char, SUM(Convert(money, m.mat1_07_03)), 101)
FROM lntmu11.matter m
GROUP BY m.con_id
ORDER BY COUNT(m.Client) DESC
如何进一步对Ccode
列进行分组,以获得有多少行的COUNT
NOFA
或NOFL
我想要的输出显示为:
╔══════════╦═══════════╦═══════════════╦═══════════════╦══════════════╗
║ Client ║ CaseCount ║ NOFACaseTotal ║ NOFLCaseTotal ║ AmtInDispute ║
╠══════════╬═══════════╬═══════════════╬═══════════════╬══════════════╣
║ Client A ║ 3548 ║ 2000 ║ 1548 ║ 5,658,307.60 ║
║ Client B ║ 3366 ║ 100 ║ 3266 ║ 2,885,649.48 ║
║ Client C ║ 3014 ║ 800 ║ 2214 ║ 2,851,507.13 ║
║ Client D ║ 2340 ║ 340 ║ 2000 ║ 3,467,207.12 ║
╚══════════╩═══════════╩═══════════════╩═══════════════╩══════════════╝
答案 0 :(得分:3)
只需使用条件聚合:
SELECT m.Client, CaseCount = COUNT(m.con_id),
CONVERT(varchar(255), SUM(Convert(money, m.mat1_07_03)), 101) as AmtInDispute
sum(case when cCode = 'NOFA' then 1 else 0 end) as NOFACaseTotal,
sum(case when cCode = 'NOFL' then 1 else 0 end) as NOFLCaseTotal,
FROM lntmu11.matter m
GROUP BY m.client
ORDER BY COUNT(m.Client) DESC;
注意:在对字符进行转换时,请始终包含长度(在T-SQL中)。
答案 1 :(得分:2)
您可以使用条件聚合来获取其他2列。使用带有CASE表达式的聚合函数来计算每个列所需的Ccode
值。
SELECT
[Client]=MAX(m.Client)
,[CaseCount]=COUNT(m.con_id)
,NOFACaseTotal = sum(case when m.Ccode = 'NOFA' then 1 else 0 end)
,NOFLCaseTotal = sum(case when m.Ccode = 'NOFL' then 1 else 0 end)
,[AmtInDispute]=CONVERT(char(50), SUM(Convert(money, m.mat1_07_03)), 101)
FROM lntmu11.matter m
GROUP BY m.con_id
ORDER BY COUNT(m.Client) DESC;
答案 2 :(得分:1)
就像Gordon和Bluefeet所说的条件聚合FTW一样!
SELECT
[Client]=MAX(m.Client)
,[CaseCount]=COUNT(m.con_id)
,[AmtInDispute]=CONVERT(char, SUM(Convert(money, m.mat1_07_03)), 101)
,[NOFACaseTotal]=sum(case when Ccode = 'NOFA' then 1 else 0 end)
,[NOFLCaseTotal]=sum(case when Ccode = 'NOFL' then 1 else 0 end)
FROM lntmu11.matter m
GROUP BY m.con_id
ORDER BY COUNT(m.Client) DESC