2016-01-06 23 views
1

看到这是我2016年的第一篇文章,祝大家新年快乐。SQL Server例外报告脚本

再次,我坚持一个棘手的报告,我必须从SQL Server中提取。

我有一个Documents两个表叫DocumentsDoctype

列:

File_Name, Date, Region, DoctypeID 

数据这里面列如下。是

DoctypeID, Document_Type 

数据这列内,如下所示:

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

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

我认为你正在寻找[Pivot](https://technet.microsoft.com/en-us/library/ms177410(v = sql.105).aspx) – JodyT

+0

HI @JodyT谢谢你的回复,我对SQL中Pivot的知识非常有限,有没有例子? – user3309798

+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,你可以阅读。

+0

嗨@Suvro,这很好,谢谢你。 – user3309798

+0

非常欢迎您@ user3309798。 – Suvro