我正在嘗試使用CTE將多個結果集合到一個結果集中,其中包含6列。使用CTE將多個結果集合到一個結果集中,並將結果集合分成一個結果集
這是我開始與查詢,它返回3個結果集,每個2行:
DECLARE @User AS VARCHAR(50)
SET @User = 'testuser'
DECLARE @LastYearEndDate AS DATETIME
DECLARE @LastMonthEndDate AS DATETIME
DECLARE @LastWeekEndDate AS DATETIME
SET @LastYearEndDate = (SELECT DATEADD(dd,-1, DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)))
SET @LastMonthEndDate = (SELECT DATEADD(d,-1,DATEADD(mm, DATEDIFF(m,0,GETDATE()),0)))
SET @LastWeekEndDate = (SELECT DATEADD(day, -1 - (DATEPART(dw, GETDATE()) + @@DATEFIRST - 2) % 7, GETDATE()))
SELECT SUM(os.db_Exp)
AS YearToDateRevenue,
COUNT(*) AS YearToDateCount
FROM tblOrderSum os
JOIN tblUserProfile up
ON os.db_RTS = up.db_UserId
WHERE os.db_Deleted = 0
AND os.db_Date39 > @LastYearEndDate
AND os.db_Date45 = '1900/01/01'
AND db_Email LIKE @User + '%'
SELECT SUM(os.db_Exp)
AS MonthToDateRevenue,
COUNT(*) AS MonthToDateCount
FROM tblOrderSum os
JOIN tblUserProfile up
ON os.db_RTS = up.db_UserId
WHERE os.db_Deleted = 0
AND os.db_Date39 > @LastMonthEndDate
AND os.db_Date45 = '1900/01/01'
AND db_Email LIKE @User + '%'
SELECT SUM(os.db_Exp)
AS WeekToDateRevenue,
COUNT(*) AS WeekToDateCount
FROM tblOrderSum os
JOIN tblUserProfile up
ON os.db_RTS = up.db_UserId
WHERE os.db_Deleted = 0
AND os.db_Date39 > @LastWeekEndDate
AND os.db_Date45 = '1900/01/01'
AND db_Email LIKE @User + '%'
輸出:
Result set 1:
YearToDateRevenue | YearToDateCount
120 3
Result set 2:
MonthToDateRevenue | MonthToDateCount
75 2
Result set 3:
WeekToDateRevenue | WeekToDateCount
18 1
有可能更簡單的方式來做到這一點,因爲我每次只切換一個參數,但這是我的嘗試:
/* Same declarations as above */
WITH cte AS (
SELECT
os.db_Exp
FROM tblOrderSum os
JOIN tblUserProfile up
ON os.db_RTS = up.db_UserId
WHERE os.db_Deleted = 0
AND os.db_Date39 > @LastYearEndDate
AND os.db_Date39 > @LastMonthEndDate
AND os.db_Date39 > @LastWeekEndDate
AND os.db_Date45 = '1900/01/01'
AND db_Email LIKE @User + '%')
SELECT
(SELECT SUM(os.db_Exp) AS YearToDateRevenue,
COUNT(*) AS YearToDateCount
FROM cte
WHERE os.db_Date39 > @LastYearEndDate)
(SELECT SUM(os.db_Exp) AS YearToDateRevenue,
COUNT(*) AS YearToDateCount
FROM cte
WHERE os.db_Date39 > @LastMonthEndDate)
(SELECT SUM(os.db_Exp) AS YearToDateRevenue,
COUNT(*) AS YearToDateCount
FROM cte
WHERE os.db_Date39 > @LastWeekEndDate)
現在我正在收到錯誤:
Msg 4104, Level 16, State 1, Line 28
The multi-part identifier "os.db_Date39" could not be bound.
Msg 4104, Level 16, State 1, Line 25
The multi-part identifier "os.db_Exp" could not be bound.
Msg 116, Level 16, State 1, Line 30
Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.
輸出我想獲得:
YearToDateRevenue | YearToDateCount | MonthToDateRevenue | MonthToDateCount | WeekToDateRevenue | WeekToDateCount
120 3 75 2 18 1
我不確定納入在CTE的參數和得到這個運行的正確方法。我不明白的任何更簡單的解決方案也會受到讚賞。我只是希望每個總和和計數在不同的列。只有一個數字被返回,因此這應該返回一行和六列。謝謝
如果您編輯您的問題,並解釋你想要得到的結果,你可能會發現,有一個具有相同的效果更加簡單查詢。 –
添加了我想要獲得的輸出和當前輸出。希望有幫助 – cfly24