计算SQL Server中的条目和数据透视表

时间:2016-11-29 13:47:37

标签: sql sql-server pivot

我有关于数据透视表和总结的问题

source select语句输出以下结构

Customer|ProductID
A       |1
A       |4
B       |3
C       |2
D       |3
D       |3
D       |4

我想将此转换为具有此结构的表格:

Customer|Count|1|2|3|4
A       |2    |1|0|0|1
B       |1    |0|0|1|0
C       |1    |0|1|0|0
D       |3    |1|0|1|1

"计数"应该是客户购买的产品数量,但我无法让它工作:(

这是SQL:

SELECT customerId, CustomerNo, [1], [2], [3], [4] FROM

(SELECT id AS customerId, 
CustomerNo,
CASE ProductType
WHEN 1 THEN 1 /* Games */
WHEN 2 THEN 2 /* Cards */
WHEN 4 THEN 3 /* Gadgets */
WHEN 5 THEN 3 /* Accessories */
WHEN 6 THEN 4 /* Smartsphone acc. */
ELSE 255
END AS Products,
FROM
ProductSales
) AS SourceTable 

PIVOT ( 
COUNT(Products)
FOR Products IN ([1], [2], [3], [4])
) AS PivotTable

这很好用,但我需要在第一个SELECT语句中添加某种COUNT,以便计算每个客户拥有的记录数。

任何帮助将不胜感激。在此先感谢:)

/汉斯

2 个答案:

答案 0 :(得分:1)

尝试使用条件聚合而不是Pivot:

{{1}}

答案 1 :(得分:1)

根据您当前的查询,使用PIVOT无问题 只需将以下列添加到SELECT。

[1]+[2]+[3]+[4] as [Count]  

演示

create table t (customer char(1),ProductID int)
insert into t values ('A',1),('A',4),('B',3),('C',2),('D',3),('D',3),('D',4)
select      customer
           ,[1]+[2]+[3]+[4] as [Count]
           ,[1],[2],[3],[4]

from        t pivot (count(ProductID) for ProductID in ([1],[2],[3],[4])) t
+----------+-------+---+---+---+---+
| customer | Count | 1 | 2 | 3 | 4 |
+----------+-------+---+---+---+---+
| A        | 2     | 1 | 0 | 0 | 1 |
+----------+-------+---+---+---+---+
| B        | 1     | 0 | 0 | 1 | 0 |
+----------+-------+---+---+---+---+
| C        | 1     | 0 | 1 | 0 | 0 |
+----------+-------+---+---+---+---+
| D        | 3     | 0 | 0 | 2 | 1 |
+----------+-------+---+---+---+---+