表1
ID product
001 LG
001 Sony
001 LG
001 LG
001 Sony
001 BPL
001 BPL
001 Samsung
002 LG
002 BPL
002 LG
...,
我想为每个人都计算每个产品的数量。
预期产出
ID BPL LG Samsung Sony
001 2 3 1 2
002 1 1 0 0
..,
如何查询每个人员的每个产品计数。
需要SQL查询帮助。
答案 0 :(得分:2)
Select ID
, Sum( Case When Product = 'BPL' Then 1 Else 0 End ) As BPL
, Sum( Case When Product = 'Sony' Then 1 Else 0 End ) As Sony
, Sum( Case When Product = 'LG' Then 1 Else 0 End ) As LG
, Sum( Case When Product = 'Samsung' Then 1 Else 0 End ) As Samsung
From Table
Group By ID
这是一个典型的交叉表问题。您可以谷歌获得许多类似的答案。
答案 1 :(得分:2)
使用PIVOT命令:
看看这个例子:
SELECT s.Name ShiftName,
h.BusinessEntityID,
d.Name DepartmentName
FROM HumanResources.EmployeeDepartmentHistory h
INNER JOIN HumanResources.Department d ON
h.DepartmentID = d.DepartmentID
INNER JOIN HumanResources.Shift s ON
h.ShiftID = s.ShiftID
WHERE EndDate IS NULL AND
d.Name IN ('Production', 'Engineering', 'Marketing')
ORDER BY ShiftName
此查询的返回表:
ShiftName BusinessEntityID DepartmentName
Day 3 Engineering
Day 9 Engineering
...
Day 2 Marketing
Day 6 Marketing
...
Evening 25 Production
Evening 18 Production
Night 14 Production
Night 27 Production
...
Night 252 Production
(194 row(s) affected)
现在您可以更改返回表格的格式:
SELECT ShiftName,
Production,
Engineering,
Marketing
FROM
(SELECT s.Name ShiftName,
h.BusinessEntityID,
d.Name DepartmentName
FROM HumanResources.EmployeeDepartmentHistory h
INNER JOIN HumanResources.Department d ON
h.DepartmentID = d.DepartmentID
INNER JOIN HumanResources.Shift s ON
h.ShiftID = s.ShiftID
WHERE EndDate IS NULL AND
d.Name IN ('Production', 'Engineering', 'Marketing')) AS a
PIVOT
(
COUNT(BusinessEntityID)
FOR DepartmentName IN ([Production], [Engineering], [Marketing])
) AS b
ORDER BY ShiftName
返回的表格如下:
ShiftName Production Engineering Marketing
Day 79 6 9
Evening 54 0 0
Night 46 0 0
(3 row(s) affected)
答案 2 :(得分:0)
通常,您不能这样做,因为输出中的列数取决于产品列中存储的不同值的数量。如果您事先知道所有可能的产品,您可以像在@Thomas的回答中那样将它们硬编码到查询中。否则,你能做的最好的是:
Select ID, product, count(*) as cnt
From Table1
Group By ID, product
这会产生如下表格:
ID product cnt
001 LG 3
001 Sony 2
001 BPL 1
001 Samsung 1
002 LG 2
002 BPL 1