3

我在下面有一个查询,我列出了所有尚未清空的交易,目标是获取一个包含所有打开的 transactionID(代表客户订单)及其发票编号的列表。

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 年。我希望查询查找与每个打开的 transactionID 的最早预订日期相对应的年份。

例如:

表格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
4

2 回答 2

1

如果您使用的是 SQL Server 2005 或更高版本,则可以使用如下窗口函数:

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
;
于 2012-09-09T16:32:57.900 回答
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) 
于 2012-09-05T10:44:41.993 回答