我正在尝试使用可变条件编写查询。无论如何在不使用联盟的情况下执行以下操作,而是使用另一个表中的日期列表?
SELECT
'2014-03-03' AS SnapshotDate
,T2.Pre_PPI_Cycle
,SUM(ISNULL(T2.Pre_PPI_Balance, 0))AS Pre_Balance
,COUNT(ISNULL(T2.Account_Number, 0)) AS Pre_Volume
,ROW_NUMBER() OVER (PARTITION BY Account_Number
ORDER BY Account_Number, SnapshotDate DESC) AS ROW
FROM #TABLE_1 AS T2
WHERE T2.SnapshotDate <= '2014-03-03'
GROUP BY T2.SnapshotDate, T2.Pre_PPI_Cycle, Account_Number
UNION
SELECT
'2014-03-04' AS SnapshotDate
,T2.Pre_PPI_Cycle
,SUM(ISNULL(T2.Pre_PPI_Balance, 0))AS Pre_Balance
,COUNT(ISNULL(T2.Account_Number, 0)) AS Pre_Volume
,ROW_NUMBER() OVER (PARTITION BY Account_Number
ORDER BY Account_Number, SnapshotDate DESC) AS ROW
FROM #PPI_3 AS T2
WHERE T2.SnapshotDate <= '2014-03-04'
GROUP BY T2.SnapshotDate, T2.Pre_PPI_Cycle, Account_Number
修改
感谢目前为止的帮助 - 只是为了澄清 - 这是我现在的代码。
SELECT
T2.Capture_Date
,T1.Pre_PPI_Cycle
,SUM(ISNULL(T1.Pre_PPI_Balance, 0))AS Pre_Balance
,COUNT(ISNULL(T1.Account_Number, 0)) AS Pre_Volume
,ROW_NUMBER() OVER (PARTITION BY T1.Account_Number
ORDER BY T1.Account_Number, T1.SnapshotDate DESC) AS ROW
FROM
#PPI_3 AS T1
INNER JOIN (SELECT CHILD.Capture_Date
FROM #DATES AS CHILD
WHERE CHILD.Capture_Date <= '2014-03-04') T2
ON T2.Capture_Date = T1.SnapshotDate
GROUP BY T2.Capture_Date, T1.SnapshotDate, T1.Pre_PPI_Cycle, T1.Account_Number
我在下面的评论中提到我希望将日期'2014-03-04'更改为保留在表#DATES中的日期列表。例如,如果日期&lt; =''2014-03-03'它返回32条记录。如果日期&lt; =''2014-03-04'它返回55条记录。我想要的是总查询返回87条记录。这就是我正在努力的部分!
感谢大家的帮助 - 感觉我们正在取得进步!
谢谢,Sam
答案 0 :(得分:0)
DECLARE @mydate smalldatetime
set @mydate = '2014-03-03';
SELECT
'2014-03-03' AS SnapshotDate
,T2.Pre_PPI_Cycle
,SUM(ISNULL(T2.Pre_PPI_Balance, 0))AS Pre_Balance
,COUNT(ISNULL(T2.Account_Number, 0)) AS Pre_Volume
,ROW_NUMBER() OVER (PARTITION BY Account_Number ORDER BY Account_Number, SnapshotDate DESC) AS ROW
FROM #TABLE_1 AS T2
INNER JOIN ( SELECT T2.ID, myDate
FROM #TABLE_1 AS T2
WHERE T2.SnapshotDate <= @mydate
) x
ON x.myDate = T2.SnapshotDate
AND x.ID = T2.ID
GROUP BY T2.SnapshotDate, T2.Pre_PPI_Cycle, Account_Number
OR
SELECT
'2014-03-03' AS SnapshotDate
,T2.Pre_PPI_Cycle
,SUM(ISNULL(T2.Pre_PPI_Balance, 0))AS Pre_Balance
,COUNT(ISNULL(T2.Account_Number, 0)) AS Pre_Volume
,ROW_NUMBER() OVER (PARTITION BY Account_Number ORDER BY Account_Number, SnapshotDate DESC) AS ROW
FROM #TABLE_1 AS T2
WHERE T2.SnapshotDate IN ( SELECT myDate
FROM #TABLE_1 AS T2
WHERE T2.SnapshotDate <= '2014-03-03' )
GROUP BY T2.SnapshotDate, T2.Pre_PPI_Cycle, Account_Number
根据您的最新动态。我会更容易做到以下几点:
SELECT
T1.Capture_Date
,T1.Pre_PPI_Cycle
,SUM(ISNULL(T1.Pre_PPI_Balance, 0))AS Pre_Balance
,COUNT(ISNULL(T1.Account_Number, 0)) AS Pre_Volume
,ROW_NUMBER() OVER (PARTITION BY T1.Account_Number
ORDER BY T1.Account_Number, T1.SnapshotDate DESC) AS ROW
FROM #PPI_3 AS T1
WHERE T1.Capture_Date IN (
SELECT CHILD.Capture_Date
FROM #DATES AS CHILD
WHERE CHILD.Capture_Date <= '2014-03-04')
GROUP BY T1.Capture_Date, T1.SnapshotDate, T1.Pre_PPI_Cycle, T1.Account_Number