0

各位大师,我需要您的帮助。

有表:

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

我需要每家餐厅上个月的 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

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
             )
于 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 回答