如果没有PIVOT,则显示GROUP BY列为列名的数据

时间:2015-03-20 19:02:27

标签: sql sql-server tsql reporting-services ssrs-2008

我的数据如下所示:

Name    Date         Hr     Min    Amt
Joe     20150320     08     00     5
Joe     20150320     08     15     3
Carl    20150320     09     30     1
Carl    20150320     09     45     2
Ray     20150320     13     00     8
Ray     20150320     13     30     6

简单的GROUP BY [名称],[日期],[Hr]将显示每个推销员的总小时数。

不使用PIVOT或动态sql,如何在小时为列的情况下显示此数据?使用PIVOT我需要详细说明每个小时,所以如果上面的数据是唯一的数据,那么将有3列数据(8,9,13)和21个空列。

我想这样做的原因是因为我想创建一个SSRS报告,其中列是小时。不幸的是,我不能使用矩阵,因为我不能按列细节排序(即点击“8”并显示从最小到最大);我已经与MS专家确认了这个限制。

所以任何帮助都表示赞赏。我们有Sql Server 2008 R2。 感谢。

2 个答案:

答案 0 :(得分:0)

Select Name    
      ,[Date]
      ,SUM(Case When Hr = '00' THEN Amt END) [00]
      ,SUM(Case When Hr = '01' THEN Amt END) [01]
      ,SUM(Case When Hr = '02' THEN Amt END) [02]
      ,SUM(Case When Hr = '03' THEN Amt END) [03]
      ,SUM(Case When Hr = '04' THEN Amt END) [04]
      ,SUM(Case When Hr = '05' THEN Amt END) [05]
      ,SUM(Case When Hr = '06' THEN Amt END) [06]
      ,SUM(Case When Hr = '07' THEN Amt END) [07]
      ,SUM(Case When Hr = '08' THEN Amt END) [08]
      ,SUM(Case When Hr = '09' THEN Amt END) [09]
      ,SUM(Case When Hr = '10' THEN Amt END) [10]
      ,SUM(Case When Hr = '11' THEN Amt END) [11]
      ,SUM(Case When Hr = '12' THEN Amt END) [12]
      ,SUM(Case When Hr = '13' THEN Amt END) [13]
      ,SUM(Case When Hr = '14' THEN Amt END) [14]
      ,SUM(Case When Hr = '15' THEN Amt END) [15]
      ,SUM(Case When Hr = '16' THEN Amt END) [16]
      ,SUM(Case When Hr = '17' THEN Amt END) [17]
      ,SUM(Case When Hr = '18' THEN Amt END) [18]
      ,SUM(Case When Hr = '19' THEN Amt END) [19] 
      ,SUM(Case When Hr = '20' THEN Amt END) [20]
      ,SUM(Case When Hr = '21' THEN Amt END) [21]
      ,SUM(Case When Hr = '22' THEN Amt END) [22]
      ,SUM(Case When Hr = '23' THEN Amt END) [23]
From TablenName
Group By Name ,[Date]

答案 1 :(得分:0)

像这样的工作?将你的关键字段放入临时表中不加入它们,这样你就可以创建所有内容,然后再查询你的内容。

select * into #Temp1 from (
select '01' as 'Pivot_Hour'
union all
select '02' as 'Pivot_Hour'
union all 
select '03' as 'Pivot_Hour'
union all
select '04' as 'Pivot_Hour'
union all
select '05' as 'Pivot_Hour'
--Put all 24 hours in....
)  
x

select * into #Temp2 from (
select 'Carl' as 'User'
union all
select 'Joe' as 'User'
union all 
select 'Ray' as 'User'
union all
select 'Dave' as 'User'
union all
select 'Seve' as 'User'
---Could select distinct from your data...
)  
x


Select * into #Temp3 from (
select '20150321' as 'Date'
union all
select '20150322' as 'Date'
union all 
select '20150323' as 'Date'
union all
select '20150324' as 'Date'
union all
select '20150325' as 'Date'
---Could select distinct from your data...
)  
x

select * 
,(select sum(yrd.amt) from Yourdata Yrd 
where yrd.Name = t2.User 
and yrd.date = t3.date 
and yrd.Hr = t1.Pivot_Hour)Amt
from #Temp1 t1,#Temp2 t2,#Temp3 t3

drop table #Temp1
drop table #Temp2
drop table #Temp3