有时找到传达'问题'的最佳方式就像找到解决方案一样困难......大声笑但是这里......
我有一张公司的桌子,我有一张相关的表格,每家公司都有一些历史...... 我想返回一个查询,其中包含每家公司最近3个“历史”条目的记录集......
所以记录集看起来像这样......
company A
history Az
history Ay
history Ax
company B
history Bz
history By
history Bx
company C
history Cz
history Cy
history Cx
我遇到的问题是如果我限制3 - 连接在那里我必须获得所有记录的最后3条记录,而不是每个公司的最后3条记录......
这是我上次尝试的内容 - 但它只是撤回了一家公司,3条记录......就是这样......(IBM DB2 9 - 但唯一应该影响的是语法限制为3 .. )
SELECT
C.CompanyName
,H.*
FROM Companies C
JOIN CompanyTypes CT ON C.fkTypeID = CT.ID
INNER JOIN (
SELECT sCH.*
FROM CompanyHistory sCH
ORDER BY sCH.DATE DESC
FETCH FIRST 3 ROWS ONLY
) H ON H.fkCompanyID = C.ID
WHERE CT.Type = 'bookstore'
我做错了什么?
答案 0 :(得分:1)
看起来DB2支持带有OVER子句的ROW_NUMBER()。我正在猜测语法,但希望这会指出你正确的方向:
SELECT
CompanyName,
SomeColumn
FROM (
SELECT
C.CompanyName,
H.SomeColumn,
ROW_NUMBER() OVER(PARTITION BY C.ID ORDER BY CH.DATE DESC)
FROM
Companies C
INNER JOIN CompanyTypes CT ON C.fkTypeID = CT.ID
INNER JOIN CompanyHistory CH ON CH.fkCompanyID = C.ID
) AS SQ
答案 1 :(得分:1)
SELECT C.CompanyName,H.*
FROM Companies C
JOIN CompanyTypes CT ON C.fkTypeID = CT.ID
INNER JOIN (
SELECT sCH.*
FROM CompanyHistory sCH
ORDER BY sCH.DATE DESC -- order desc so we can count
) H ON H.fkCompanyID = C.ID
WHERE CT.Type = 'bookstore'
and 3>(select count(*) -- at most 2 previous occurances
from CompanyHistory ich
where ich.fkCompanyID=C.ID -- same company
and datediff(d,ich.date,H.date)<0) -- but dates less than the row's date
基本上我计算每个公司的前一行,并且在我们超过2时删除行(+当前行为3)。您需要按日期desc对CompanyHistory
表进行排序才能使其正常工作。
您可能需要将datediff
替换为SQL风格的函数,我才真正了解SQL Server。