我需要从每天和每个团队的数据库中选择一些信息。我想知道每个团队每天购买的物品数量。例如,如果在2012-11-21购买了6件物品,我希望我的结果显示:团队1买了3件物品,团队2 - 2件物品和最后一团队1件物品。我可以使用以下内容获取一个团队的信息:
select count(CONVERT(date, getdate())) as Team1
from items
where team = 1
group by CONVERT(date, getdate())
但我不确定如何获得所有团队所需的信息。
修改
我需要结果是这样的:
Date |Team1 | Team2 | Team3
2012-11-21|2 items | 3 items | 0 items
我的表结构是这样的:Date, Product, Price, Team
。
答案 0 :(得分:0)
您需要GROUP BY
团队和日期。
SELECT datecol, team, COUNT(*)
FROM items
GROUP BY datecol, team
根据您的更新要求而不知道您的DBMS是什么:
SELECT a.datecol AS 'Date',
(SELECT COUNT(*) FROM items WHERE datecol = a.datecol AND team = '1') AS 'Team1',
(SELECT COUNT(*) FROM items WHERE datecol = a.datecol AND team = '2') AS 'Team2',
(SELECT COUNT(*) FROM items WHERE datecol = a.datecol AND team = '3') AS 'Team3'
FROM items a
GROUP BY a.datecol
答案 1 :(得分:0)
你需要的是PIVOT
你的桌子是这样的:
SELECT
Date,
SUM(CASE WHEN team = 'team1' THEN 1 ELSE 0 END) 'team1',
SUM(CASE WHEN team = 'team2' THEN 1 ELSE 0 END) 'team2',
SUM(CASE WHEN team = 'team3' THEN 1 ELSE 0 END) 'team3'
FROM Tablename
GROUP BY date;