将子查询分组在一行中

时间:2013-10-08 01:05:52

标签: sql sql-server

ClientID  Amount     flag
MMC          600     1  
MMC          700     1
FDN          800     1
FDN          350     2
FDN          700     1

使用sql server,下面的查询我从FDN得到2行。我只想将客户端值组合在一行中。 输出应该像

Client  gtcount, totalAmountGreaterThan500  lscount,AmountLessThan500
MMC  2  1300               0        0
FDN  2      1500               1        350 
SELECT 
    f.ClientID,f.flag,    
case when flag = 1 then count(*) END as gtcount,
    SUM(CASE WHEN flag = 1 THEN Amount END) AS totalAmountGreaterThan500,
case when flag = 2 then count(*) END as lscount,
    SUM(CASE WHEN Flag = 2 THEN Amount END) AS AmountLessThan500,
from
    ( select ClientID, Amount,flag from #myTable)f
group by ClientID,f.flag

2 个答案:

答案 0 :(得分:1)

尝试

SELECT ClientID,    
       SUM(CASE WHEN flag = 1 THEN 1 ELSE 0 END) AS gtcount,
       SUM(CASE WHEN flag = 1 THEN Amount ELSE 0 END) AS totalAmountGreaterThan500,
       SUM(CASE WHEN flag = 2 THEN 1 ELSE 0 END) AS lscount,
       SUM(CASE WHEN Flag = 2 THEN Amount ELSE 0 END) AS AmountLessThan500
  FROM Table1
 GROUP BY ClientID

输出:

| CLIENTID | GTCOUNT | TOTALAMOUNTGREATERTHAN500 | LSCOUNT | AMOUNTLESSTHAN500 |
|----------|---------|---------------------------|---------|-------------------|
|      FDN |       2 |                      1500 |       1 |               350 |
|      MMC |       2 |                      1300 |       0 |                 0 |

这是 SQLFiddle 演示

答案 1 :(得分:0)

您的所需输出似乎已关闭 - 没有任何mmc条记录小于500.您可以使用sumcase为每个字段完成此操作,删除来自flag

group by
SELECT 
    ClientID,    
    SUM(CASE WHEN flag = 1 THEN 1 END) as gtcount,
    SUM(CASE WHEN flag = 1 THEN Amount END) AS totalAmountGreaterThan500,
    SUM(CASE WHEN flag = 2 THEN 1 END) as ltcount,
    SUM(CASE WHEN Flag = 2 THEN Amount END) AS AmountLessThan500
from myTable
group by ClientID

另一方面,不确定为什么需要Flag字段。如果它仅用于表示少于记录,则只需将逻辑添加到查询中:

SUM(CASE WHEN Amount <= 500 Then ...)