查询使用报告向导制作矩阵样式.rdl报告

时间:2013-06-03 03:18:46

标签: sql reporting-services matrix ssrs-2008

我需要帮助编写矩阵样式报告的查询。

我的数据采用以下格式

id    body_part   incident_type1  incident_type2   incident_type3 
1     head        PPE             null             null 
2     ankle       Unsafe Act      Facility         null
3     hand        null            null             null
4     head        Facility        PPE              Unsafe Act

我希望行作为主体部分和列成为事件类型。如果incident_type1为null,那么我想在“n / a”列中进行计数。但是,如果incident_type2和/或3为null,我不希望那些计入“n / a”列。

            Facility    Unsafe Act    PPE     N/A
ankle        1            1            0       0
hand         0            0            0       1
head         1            1            2       0

2 个答案:

答案 0 :(得分:0)

这是实现此目的的一种方式:

select body_part
  , Facility = sum(case when incident_type1 = 'Facility' or incident_type2 = 'Facility'  or incident_type3 = 'Facility' then 1 else 0 end)
  , [Unsafe Act] = sum(case when incident_type1 = 'Unsafe Act' or incident_type2 = 'Unsafe Act'  or incident_type3 = 'Unsafe Act' then 1 else 0 end)
  , PPE = sum(case when incident_type1 = 'PPE' or incident_type2 = 'PPE'  or incident_type3 = 'PPE' then 1 else 0 end)
  , [N/A] = sum(case when incident_type1 is null then 1 else 0 end)
from Incidents
group by body_part
order by body_part

SQL Fiddle with demo

这假设已知的事件类型,并且同一行不会多次具有相同的事件类型。

答案 1 :(得分:0)

我能够通过创建存储过程来实现这一点,我将数据插入到临时表中。然后,我可以使用带有“EXEC SP_Name”的报告向导作为查询。然后我选择Body_part作为我的行,Incident_type作为我的列,Totals作为我的数据。

CREATE TABLE #tmp
(
    Body_part VARCHAR(200) NOT NULL,
    Incident_type VARCHAR(250) NOT NULL,
)

INSERT INTO #tmp
SELECT ISNULL(Body_part, 'N/A'), ISNULL(Incident_type, 'N/A')
FROM [safety].vwIncomingPINS
WHERE submitted_on >= dateadd(year,-1,getdate()) AND submitted_on <=getdate()

INSERT INTO #tmp
SELECT ISNULL(Body_part, 'N/A'), Incident_type2
FROM [safety].vwIncomingPINS
WHERE submitted_on >= dateadd(year,-1,getdate()) AND submitted_on <=getdate() AND Incident_type2 IS NOT NULL

INSERT INTO #tmp
SELECT ISNULL(Body_part, 'N/A'), Incident_type3
FROM [safety].vwIncomingPINS
WHERE submitted_on >= dateadd(year,-1,getdate()) AND submitted_on <=getdate() AND Incident_type3 IS NOT NULL

SELECT Body_part, Incident_type, count(*) AS Totals from #tmp
GROUP BY Body_part, Incident_type