我有一张桌子,一张简单的桌子,只有3个字段。
ID Type Date
数据示例(记录集显示3个中的3个)
154 |页面| 2010-02-08
154 |链接| 2010-02-08
154 |形式| 2010-02-08
Id:只是客户端的ID
类型:只能填充3件事('form','page','link')
日期:只是创建日期
每个ID都有多个条目。
我想创建一个存储过程或查询,它为我提供以下输出
所需的OutPut / Count
的示例ID |链接|表格|页
154 | 75 | 40 | 100
我只想要计算每种类型,所以我不必进行3次单独的SQL调用来获取每种类型的计数。任何帮助将不胜感激,这将需要转到存储过程,我想要的基础是ID。
提前致谢
答案 0 :(得分:4)
你可能想要这样的东西
Select id
, Sum(Case when Type='Link' then 1 else 0 end) as Links
, Sum(Case when Type='Forms' then 1 else 0 end) as Forms
, Sum(Case when Type='Page' then 1 else 0 end) as Pages
From SomeTable
Group by ID
答案 1 :(得分:2)
简单的PIVOT查询应解决问题
SELECT *
FROM SimpleTable
PIVOT
(
COUNT(Date)
FOR Type IN ([Link], [Form], [Page])
) AS t
答案 2 :(得分:1)
尝试一下(sql server)
SELECT
[ID]
,SUM( CASE TYPE WHEN 'LINK' THEN 1 ELSE 0 END ) AS [Link]
,SUM( CASE TYPE WHEN 'FORMS' THEN 1 ELSE 0 END ) AS [FORMS]
,SUM( CASE TYPE WHEN 'PAGE' THEN 1 ELSE 0 END ) AS [Page]
FROM yourTable
GROUP BY ID --remove this line if you are passing in a single @GivenID
WHERE ID=@GivenID --remove this line if you want counts for all IDs (returns many rows)