如何获取特定列的分组输出,如下所示在SQL中?

时间:2017-08-03 15:32:38

标签: sql sql-server

有一个包含两列的表和此查询:

select SupplierName, Acknowledge 
from tbPOValidation

返回此结果集:

SupplierName         Acknowledge
--------------------------------
SUPPLIER COMPANY        1
CANADA SUPPLIERS        0
MOTION INDUSTRIES       0
SUPPLIER COMPANY        1
CANADA SUPPLIERS        0
INDUSTRY CORP           1
CORP SUPPLIERS          1
JAMES SUPPLIERS         NULL
MOTION INDUSTRIES       NULL

我希望输出看起来像这样(ack 1 = yes,0 = no,Null = Null)

SupplierName      YES   NO  NULL
--------------------------------
JAMES SUPPLIERS   0     0   1
INDUSTRY CORP     1     0   0
CANADA SUPPLIERS  0     2   0
MOTION INDUSTRIES 0     1   1
SUPPLIER COMPANY  2     0   0
CORP SUPPLIERS    1     0   0

我怎么能得到这个?

1 个答案:

答案 0 :(得分:4)

SQL下面会对你有帮助。

SELECT SupplierName, 
    SUM(CASE WHEN Acknowledge = 1 THEN 1 ELSE 0 END) AS 'YES',
    SUM(CASE WHEN Acknowledge = 0 THEN 1 ELSE 0 END) AS 'NO',
    SUM(CASE WHEN Acknowledge IS NULL THEN 1 ELSE 0 END) AS 'NULL' 
FROM tbpovalidation
GROUP BY SupplierName