我正在编写一份报告,需要显示一周的收据,按地点分组,每周的每一天都有一个单独的列。这将通过SSRS和SQL Server 2008 R2提供。最终结果应如下所示:(但对于一周中的所有7天)
Location Monday Tuesday
Building3 $100 $75
Building4 $25 $35
Building5 $105 $21
我编写了以下T-SQL SELECT语句,以便从我的报表变量(@reporting)中获取此数据。然后打算按位置对输出进行分组,以获得上面显示的布局。
原始数据列出了单行中的收货日期,总计和位置。我想转动数据,以便星期几显示在最前面。必须有一个比你在下面看到的更好的方法。有帮助吗?
SELECT
LocationKey.Location
,Sunday.Cost as Sunday
,Monday.Cost as Monday
FROM
(
SELECT DISTINCT Location
FROM @reporting
WHERE Location NOT IN ('Building01', 'Building02', '')
) AS LocationKey
LEFT JOIN
(SELECT
sunday.Location
,sunday.Cost
FROM @reporting as sunday (nolock)
WHERE DATEPART(weekday,sunday.ReceiptDate)= 1
) AS Sunday
ON Sunday.Location = LocationKey.Location
LEFT JOIN
(SELECT
Monday.Location,
Monday.Cost
FROM @reporting as Monday (nolock)
WHERE DATEPART(weekday,Monday.ReceiptDate)= 2
) AS Monday
ON Monday.Location = LocationKey.Location
答案 0 :(得分:6)
执行此操作的最简单方法可能是PIVOT上的DATENAME。
SELECT location,
[Saturday],
[Sunday],
[Monday],
[Tuesday],
[Wednesday],
[Thursday],
[Friday]
FROM (SELECT COST,
location,
Datename(weekday, receiptdate) DAY
FROM @reporting
WHERE location NOT IN ( 'Building01', 'Building02', '' )) p
PIVOT (
SUM (COST)
FOR DAY IN ( [Saturday], [Sunday], [Monday], [Tuesday], [Wednesday],
[Thursday], [Friday]) ) pvt
请参阅此data.se query
另一种方法是使用多个自连接但不使用子查询。这里的关键是Join Clause
SELECT LocationKey.Location,
SUM(Sunday.Cost) As [Sunday],
SUM(Monday.Cost) As [Monday],
SUM(Tuesday.Cost) As [Tuesday],
SUM(Wednesday.Cost) As [Wednesday],
SUM(Thursday.Cost) As [Thursday],
SUM(Friday.Cost) As [Friday],
SUM(Saturday.Cost) As [Saturday]
FROM
(SELECT DISTINCT Location
FROM @reporting
WHERE Location NOT IN ('Building01', 'Building02', '')) LocationKey
LEFT JOIN @Reporting Sunday
ON LocationKey.Location = Sunday.Location
AND DATEPART(weekday,sunday.ReceiptDate)= 1
LEFT JOIN @Reporting Monday
ON LocationKey.Location = Monday.Location
AND DATEPART(weekday,Monday.ReceiptDate)= 2
LEFT JOIN @Reporting Tuesday
ON LocationKey.Location = Tuesday.Location
AND DATEPART(weekday,Tuesday.ReceiptDate)= 3
LEFT JOIN @Reporting Wednesday
ON LocationKey.Location = Wednesday.Location
AND DATEPART(weekday,Wednesday.ReceiptDate)= 4
LEFT JOIN @Reporting Thursday
ON LocationKey.Location = Thursday.Location
AND DATEPART(weekday,Thursday.ReceiptDate)= 5
LEFT JOIN @Reporting Friday
ON LocationKey.Location = Friday.Location
AND DATEPART(weekday,Friday.ReceiptDate)= 6
LEFT JOIN @Reporting Saturday
ON LocationKey.Location = Saturday.Location
AND DATEPART(weekday,Saturday.ReceiptDate)= 7
您应该注意,您应该拨打SET DATEFIRST
或使用@@DATEFIRST
的偏移量来保护您的查询免受默认设置的影响,当您使用DATEPART(weekday..
时更改并破坏您的查询
答案 1 :(得分:0)
此PIVOT查询可以为您提供所需内容:
select Location, Cost_D1, Cost_D2, Cost_D3, Cost_D4, Cost_D5, Cost_D6, Cost_D7
from (
select Location, 'Cost_D' + convert(varchar,datepart(weekday,ReceiptDate)) as FieldName, Cost
from @reporting
) s
pivot
(
sum(Cost)
for FieldName
in (Cost_D1, Cost_D2, Cost_D3, Cost_D4, Cost_D5, Cost_D6, Cost_D7)
) p