2013-01-16 55 views
0

您好,大師我需要您的幫助。如何在返回兩列的子查詢中使用運算符IN

具有表:

DataCollection 
================== 
PK   Code 
smallint  RestaurantCode 
smallint  Year 
tinyint  Month 
money   Amount 
money   AccumulativeMonthsAmount 
... 

我需要爲LastMonth的AccumulateAmount每個餐廳。

首先,我拿到每餐廳上個月的「當年」(這種情況下):

SELECT RestaurantCode, MAX(Month) as Month FROM DataCollection 
WHERE (Year >= 2012 AND YEAR <= 2012) GROUP BY RestaurantCode 

現在我想使用它作爲子查詢,以獲得最後 - AccumulativeMonthsAmount:

SELECT AccumulativeMonthsAmount FROM DataCollection 
WHERE (RestaurantCode, Month) 
    IN (SELECT RestaurantCode, MAX(Month) as Month FROM DataCollection 
     WHERE (Year >= 2012 AND YEAR <= 2012) GROUP BY RestaurantCode) 

但是,運營商IN,不工作,我應該怎麼做?

按年份和月份分類樣本數據:

RestCode Amount Accumulative Year Month 
123  343.3 345453.65 2012 12 
123  124.7 345329.00 2012 11 
... 
122  312.2 764545.00 2012 12 
122  123.4 764233.00 2012 11 
... 
999  500.98 2500.98 2012  6 
999  100.59 2000.00 2012  5 
... 

我想獲得累計對每家餐廳的最後一個月:

RestCode Accumulative Month 
123   345453.65 12 
122   764545.00 12 
99   2500.98  6 
... 
+3

您使用合適的JOIN,而不是使用子查詢。 –

+0

似乎我失去了秒數,在哪裏可以回答問題。 –

+0

似乎是一個經典的['最大 - 每組 - >](http://stackoverflow.com/questions/tagged/greatest-n-per-group+sql-server)問題。 –

回答

1

該語法在SQL Server中不允許。你可以做同樣的事情與EXISTS

SELECT AccumulativeMonthsAmount 
FROM DataCollection dc 
WHERE exists (select 1 
       from PAL_Entries_Relatives er 
       where (Year >= 2012 AND YEAR <= 2012) 
       group by RestaurantCode 
       having er.RestaurantCode = dc.RestaurantCode and 
        max(er.month) = dc.Month 
      ) 
+0

+1無需排序的優秀模式;) –

3
SELECT dc.AccumulativeMonthsAmount 
    FROM dbo.DataCollection AS dc 
    INNER JOIN 
    (
    SELECT RestaurantCode, MAX(Month) 
     FROM dbo.PAL_Entries_Relatives 
     WHERE [Year] = 2012 
     GROUP BY RestaurantCode 
) AS r(rc, m) 
ON dc.RestaurantCode = r.rc 
AND dc.[Month] = r.m; 

隨着變更的要求:

;WITH x AS 
(
    SELECT RestCode, Accumulative, [Month], 
    rn = ROW_NUMBER() OVER (PARTITION BY RestCode ORDER BY [Month] DESC) 
    FROM dbo.DataCollection -- or is it dbo.PAL_Entries_Relatives? 
) 
SELECT RestCode, Accumulative, [Month] 
    FROM x 
    WHERE rn = 1 
    ORDER BY [Month] DESC, RestCode DESC; 
+0

@Marlin Pierce和大家,對不起我犯了一個錯誤,表** PAL_Entries_Relatives **是同一張表** DataCollection **。 –

+0

@zerazobz那麼你能顯示樣本數據和期望的結果嗎?如果他們是同一張桌子,那麼你的查詢對我來說並沒有什麼意義。 –

+0

我用樣本數據和期望的結果更新了答案。 –

0
SELECT AccumulativeMonthsAmount 
FROM DataCollection 
    INNER JOIN PAL_Entries_Relatives 
    ON DataCollection.RestaurantCode = PAL_Entries_Relatives.RestaurantCode 
WHERE (Year >= 2012 AND YEAR <= 2012) 
GROUP BY DataCollection.RestaurantCode 
HAVING AccumulativeMonthsAmount.Month = MAX(PAL_Entries_Relatives.Month) 
相關問題