SQL 服务器:多列的唯一值总和
SQL Server: Sum of Unique values for multiple columns
使用 SQL 服务器,我有一个 table,如下例 table 所示。我需要每个列的所有唯一值的总和 "BookOrder, StationaryOrder, and Printing Order"。
样本 TABLE:
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 中实现这个目标?
谢谢
做一个group by
,count(distinct column)
来数:
Select KeyIDCustomerID,
COUNT(distinct BooksOrder) TotalBookOrders,
COUNT(distinct StationaryOrder) TotalStationaryOrder,
COUNT(distinct PrintingOrder) TotalPrintingOrder
from tablename
group by KeyIDCustomerID
我认为
的恰当用语
sum of all the unique values per the columns
是"count of unique values"
COUNT (DISTINCT column_name)
returns 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
使用 SQL 服务器,我有一个 table,如下例 table 所示。我需要每个列的所有唯一值的总和 "BookOrder, StationaryOrder, and Printing Order"。
样本 TABLE:
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 中实现这个目标?
谢谢
做一个group by
,count(distinct column)
来数:
Select KeyIDCustomerID,
COUNT(distinct BooksOrder) TotalBookOrders,
COUNT(distinct StationaryOrder) TotalStationaryOrder,
COUNT(distinct PrintingOrder) TotalPrintingOrder
from tablename
group by KeyIDCustomerID
我认为
的恰当用语sum of all the unique values per the columns
是"count of unique values"
COUNT (DISTINCT column_name)
returns 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