Вероятно, самый простой способ сделать это - 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
Другой способ - использовать несколько самостоятельных соединений, но не выполнять подзапросы.Ключевым моментом здесь является предложение о присоединении
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..