看到这是我2016年的第一篇文章,祝大家新年快乐。
再次,我遇到了一个棘手的报告,我必须从SQL Server中获取。
我有两个名为Documents
和Doctype
Documents
中的列:
File_Name, Date, Region, DoctypeID
此列中的数据如下。
00001,2016-01-06,JHB,1d187ecc
00001,2016-01-06,JHB,bccc05f9
00001,2016-01-06,JHB,fe697be0
00001,2016-01-06,JHB,bbae8c73
00002,2016-01-06,JHB,1d187ecc
00002,2016-01-06,JHB,bccc05f9
00002,2016-01-06,JHB,fe697be0
Doctype
中的列:
DoctypeID, Document_Type
此列中的数据如下。
1d187ecc, Collection
bccc05f9, Image
fe697be0, Log
bbae8c73, Sent to warehouse.
我的查询需要使用上面的数据给出以下结果。
File_Name,Collection, Image, Log, Sent to Warehouse,Region
00001, 1, 1, 1, 1, JHB
00002, 1, 1, 1, 0, JHB
我希望上述内容有道理,我将如何做到这一点?
提前谢谢大家。
答案 0 :(得分:4)
你可以试试这个:
SELECT FILE_NAME, ISNULL([Collection],0) AS [Collection], ISNULL([Image],0) AS [Image],
ISNULL([Log],0) AS [Log], ISNULL([Sent to warehouse],0) AS [Sent to warehouse], Region
FROM (
SELECT FILE_NAME, Document_Type, COUNT(Document_Type) AS Frequency, Region
FROM documents d,doctype dt WHERE d.DoctypeID = dt.DoctypeID
GROUP BY Document_Type, FILE_NAME,REGION
) AS s
PIVOT
(
SUM(Frequency)
FOR [Document_Type] IN ([Collection], [Image], [Log], [Sent to warehouse])
)AS pvt
以下是您可以阅读的详细信息reference。