在TSQL中进行计数的最佳方法

时间:2018-09-03 19:03:02

标签: sql sql-server tsql

我在TSQL方面不太出色,我想以这种方式编写报告:

输入:表A

ID   Company Product  Flag
1    A        Car        Y
2    A        Van        N
3    B        Van        Y
4    A        Part       N

输出

Company     Y     N
A           1     2
B           1     0

如果可以协助TSQL ...

4 个答案:

答案 0 :(得分:3)

您可以使用条件聚合:

SELECT Company
    ,SUM(CASE WHEN Flag = 'Y' THEN 1 ELSE 0 END) AS Y
    ,SUM(CASE WHEN Flag = 'N' THEN 1 ELSE 0 END) AS N
FROM tab
GROUP BY Company

答案 1 :(得分:3)

您正在寻找条件聚合:

select company,
       sum(case when flag = 'Y' then 1 else 0 end) as num_y,
       sum(case when flag = 'N' then 1 else 0 end) as num_n
from t
group by company;

答案 2 :(得分:1)

您可以使用CASE表达式(人们称其为“ 条件聚合”)来按此计数每个客户的标记产品(当{{1} }列为空):

Product

或者您可以使用此PIVOT查询,这是编写以上内容的一种简短形式:

SELECT Company
  , COUNT(CASE Flag WHEN 'Y' THEN Product END) AS Y
  , COUNT(CASE Flag WHEN 'N' THEN Product END) AS N
FROM YourTable
GROUP BY Company;

答案 3 :(得分:0)

用例何时

    select company,
   sum(case when flag='Y' then 1 else 0 end) as Y,
   sum(case when flag='N' then 1 else 0 end) as N from tabe_data
   group by company