0

こんにちはマスター私はあなたの助けが必要です。

テーブルを持つ:

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

これをサブクエリとして使用して、 Last - 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
...
4

3 に答える 3

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;
于 2013-01-16T20:33:13.193 に答える
1

その構文はSQLServerでは許可されていません。あなたは次のように似たようなことをすることができます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
             )
于 2013-01-16T20:34:25.607 に答える
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)
于 2013-01-16T20:37:39.053 に答える