SQL Server:多列的唯一值的总和

时间:2015-04-28 12:21:58

标签: sql sql-server sql-server-2008 sql-server-2008-r2 sql-server-2012

使用SQL Server,我有一个表,如下面的示例表所示。我需要为“BookOrder,StationaryOrder和Printing Order”列提供所有唯一值的总和。

样本表:

KeyIDCustomer   BooksOrder  StationaryOrder PrintingOrder
29945843         1070756    1891514            198876
29945843         1070756    1893827            198876
29945843         1070758    1891514            198876
29945843         1070758    1893827            198876

我正在使用以下编码来实现此目标。

Select DISTINCT KeyIDCustomerID,
Sum(Case when BooksOrder is not null then 1 else 0 End) TotalBookOrders,  
Sum(Case when StationaryOrder is not null then 1 else 0 End) TotalStationaryOrder,
Sum(Case when PrintingOrder is not null then 1 else 0 End)TotalPrintingOrder

使用此编码获得如下结果

  KeyIDCustomerID   TotalBookOrders TotalStationaryOrder    TotalPrintingOrder
   29945843                    4                       4                    4

我希望结果像这样

  KeyIDCustomerID   TotalBookOrders TotalStationaryOrder    TotalPrintingOrder
   29945843                    2                       2                    1

我有没有办法在SQL中实现这个目标?

谢谢

2 个答案:

答案 0 :(得分:5)

我认为适当的术语

  

每列的所有唯一值的总和

是“唯一值的计数”

COUNT (DISTINCT column_name)返回column_name

中唯一的非空值的数量
Select 
KeyIDCustomerID,
COUNT(DISTINCT BooksOrder) as TotalBookOrders,  
COUNT(DISTINCT StationaryOrder) as TotalStationaryOrder,
COUNT(DISTINCT PrintingOrder) as TotalPrintingOrder
FROM SAMPLE_TABLE
GROUP BY KeyIDCustomerID

答案 1 :(得分:4)

执行group bycount(distinct column)计算:

Select KeyIDCustomerID,
       COUNT(distinct BooksOrder) TotalBookOrders,  
       COUNT(distinct StationaryOrder) TotalStationaryOrder,
       COUNT(distinct PrintingOrder) TotalPrintingOrder
from tablename
group by KeyIDCustomerID