如何在sql server中计数和求和

时间:2017-09-22 09:22:22

标签: sql sql-server

我有以下表格T1

ID     Type        Amount
1      1           100
2      2           100
3      2           100
4      2           100
5      1           100
6      1           100
7      2           100
8      1           100
9      1           100

我需要如下结果

TotalRecods  Type1Recods type2Recods  Type1Amount type2Amount
9            5           4            500         400

我正在尝试

SELECT     COUNT(id) AS TotalRecords , 
           COUNT(type) AS Type1Records, 
           COUNT(type) AS Type2Records, 
           SUM(Amount ) AS Type1Amount, 
           SUM(Amount) AS Type2Amount 
 FROM         T1

返回

TotalRecords Type1Records Type2Records Type1Amount Type2Amount
9            9            9            900         900

我不明白如何在类型上过滤它。可能是我缺少的一个简单步骤。

3 个答案:

答案 0 :(得分:10)

SELECT
        COUNT(*) [TotalRecords],
        COUNT(CASE WHEN [Type] = 1 THEN 1 END) [Type1Records],
        COUNT(CASE WHEN [Type] = 2 THEN 1 END) [Type2Records],
        SUM(CASE WHEN [Type] = 1 THEN [Amount] END) [Type1Amount],
        SUM(CASE WHEN [Type] = 2 THEN [Amount] END) [Type2Amount]
    FROM
        [t];

请注意,如果某些类型没有记录,COUNT将返回0,但SUM的结果将NULL。如果您希望0结果也来自SUM,则可以使用它:

SUM(CASE WHEN [Type] = 1 THEN [Amount] ELSE 0 END) [Type1Amount]

答案 1 :(得分:1)

您可以使用CASE表达式来实现它。

<强>查询

select count(*) as [TotalRecods],
sum(case when [Type] = 1 then 1 else 0 end) as [Type1Recods],
sum(case when [Type] = 2 then 1 else 0 end) as [Type2Recods],
sum(case when [Type] = 1 then Amount end) as [Type1Amount],
sum(case when [Type] = 2 then Amount end) as [Type2Amount],
from your_table_name;

答案 2 :(得分:0)

试试这个:

 SELECT     COUNT(id) AS TotalRecods , 
               (SELECT COUNT(type) FROM T1 WHERE type = 1) AS Type1Recods, 
               (SELECT COUNT(type) FROM T1 WHERE type = 2) AS Type2Recods, 
               (SELECT SUM(Amount ) FROM T1 WHERE type = 1) AS Type1Amount, 
               (SELECT SUM(Amount ) FROM T1 WHERE type = 2) AS Type2Amount 
     FROM   T1