Sql分组查询

时间:2015-07-16 18:48:01

标签: sql sql-server

我想知道如何获取查询以将这些分组放入一行,这样我就可以将它放入vb.net数据网格中。

例如编号,公司名称,当前,31-60,61-90 例如公司A,但是将所有人分组都放在一条线上。

104680777, Company A, 643546.344, 34534534.77, 3454.55

甚至可以在下面进行此查询。我不得不这样做。

select sum(Amount), DunsNum, CompanyName, Age
from tblARAged
group by DunsNum, Age, CompanyName


Amount      Num        CompanyName             Age  
63546.344   104680777   Company a   1   
34534534.77 104680777   Company a   2   
3454.55 104680777   Company a   3   
3453453.66  186830733   Company b   1   
345342.45   186830733   Company b   2   
4542.55 186830733   Company c   3   
3434.55 26409797    Company c   1   
345345  26409797    Company c   2   

1与当前相关,2与31-60相关,3与年龄61-90相关

1 个答案:

答案 0 :(得分:0)

我会做Nimesh所说的,尽管我会做一些调整。您希望尽可能晚地进行聚合:

SELECT DunsNum , CompanyName , SUM(CASE WHEN ( Age = 1 ) THEN Amt ELSE 0 END) AS [Amount_Cur] , SUM(CASE WHEN ( Age = 2 ) THEN Amt ELSE 0 END) AS [Amount_31-60] , SUM(CASE WHEN ( Age = 3 ) THEN Amt ELSE 0 END) AS [Amount_61-90] FROM tblARAged GROUP BY DunsNum , CompanyName;

我还没有测试过这段代码