SQL,根据分组选择的最小值从第二个表中获取值

时间:2012-09-05 10:41:44

标签: sql sql-server join

我在下面有一个查询,我列出了所有未被清空的交易,目标是获取一个列表,其中包含所有已打开的transactionID(代表一个客户端)及其invoicenumber。

Table 1
transactionID
bookdate
cost
year

Table 2
transactionID
invoice
year

SELECT 1.transactionID, Sum(cost), 1.Max(bookdate), 2.invoice
FROM 1
LEFT JOIN 2
ON 1.transactionID = 2. transactionID AND 1.year = 2.year
GROUP BY 1.transactionID, 2.invoice
HAVING (Sum(cost)<>0)

我的问题是每年都会重复使用transactionID,这就是为什么我需要检查年份是否与实际的transactionID和表2中的发票相对应。

每个transactionID都有多个具有不同预订日期的交易。这意味着一个交易可能发生在2011年,一个发生在2012年。我希望查询查找与每个打开的交易ID最早的预订日期相对应的年份。

例如:

表1

1 | 20120101 | -20  | 2012
2 | 20120501 | -100 | 2012
2 | 20110501 | 100  | 2012
1 | 20110801 | 50   | 2011

表2

1 | invoice X   | 2012
2 | invoice Y   | 2012
1 | invoice old | 2011

结果应为

1 | 30 USD | Invoice old

2 个答案:

答案 0 :(得分:1)

如果您使用的是SQL Server 2005或更高版本,则可以使用window这样的函数:

WITH summedAndRanked AS (
  SELECT
    [1].transactionID,
    [2].invoice,
    totalCost    = SUM(cost)     OVER (PARTITION BY [1].transactionID),
    lastBookDate = MAX(bookdate) OVER (PARTITION BY [1].transactionID),
    rnk          = DENSE_RANK()  OVER (PARTITION BY [1].transactionID ORDER BY [1].year),
  FROM [1]
    LEFT JOIN [2]
      ON [1].transactionID = [2].transactionID
     AND [1].year = [2].year
)
SELECT DISTINCT
  TransactionID,
  totalCost,
  lastBookDate,
  invoice
FROM countedAndRanked
WHERE totalCost <> 0
  AND rnk = 1
;

答案 1 :(得分:0)

我认为你差不多了 - 试试

SELECT 1.transactionID, 1.Year, Sum(cost), Max(1.bookdate), 2.invoice 
FROM 1 
LEFT JOIN 2 
ON 1.transactionID = 2. transactionID AND 1.year = 2.year 
GROUP BY 1.transactionID, 1.Year, 2.invoice
HAVING (Sum(cost)<>0)