我有一个表(SQL Server),我在其中存储所有自动化测试用例的运行状态,我试图提出一个SQL查询来检索每个runid的状态,但是我遇到了一些问题问题。
表中数据的示例:
KRUNID | KTIME | FK_TC_ID | NOPART | STATUS | ENV
-------+----------------+------------+--------+--------+-----
4180-2 | 20190109080000 | TC0001 | 123456 | Passed | INT
4180-2 | 20190109080100 | TC0002 | 123457 | Failed | INT
4180-2 | 20190109080200 | TC0003 | 123458 | Passed | INT
4180-2 | 20190109080400 | TC0002 | 123459 | Passed | INT
现在,我有了这个查询(join语句用于显示实际的测试用例名称和业务域):
SELECT KRUNID, TD_NAME, TS_NAME, FK_TC_ID, TC_DISPLAYNAME, NOPARTENAIRE,
ENV, STATUS FROM RU_RUNSTATUS
INNER JOIN TC_TESTCASES ON K_TC_ID = FK_TC_ID
INNER JOIN TS_TCSUBDOMAINS ON K_TS_ID = FK_TS_ID
INNER JOIN TD_TCDOMAINS on K_TD_ID = FK_TD_ID
WHERE KRUNID = '418-2'
ORDER BY FK_TS_ID, K_TC_ID
该查询是基本查询,除在我只希望基于KTIME的最后一行(由于各种原因,我不想基于STATUS进行过滤)而只有两行TC0002时,该查询工作正常。
我没有找到修改查询以获取所需结果的正确方法。我该怎么办?
谢谢
答案 0 :(得分:0)
我认为本文可以得到答复:Get top 1 row of each group
您的查询的限制由FK_TC_ID分配,并由KTIME排序
;WITH cte AS
(
SELECT FK_TS_ID, KRUNID, TD_NAME, TS_NAME, FK_TC_ID , TC_DISPLAYNAME, NOPARTENAIRE,
ENV, STATUS, ROW_NUMBER() OVER (PARTITION BY FK_TC_ID ORDER BY KTIME DESC) AS rn
FROM RU_RUNSTATUS
INNER JOIN TC_TESTCASES ON K_TC_ID = FK_TC_ID
INNER JOIN TS_TCSUBDOMAINS ON K_TS_ID = FK_TS_ID
INNER JOIN TD_TCDOMAINS on K_TD_ID = FK_TD_ID
WHERE KRUNID = '418-2'
)
SELECT *
FROM cte
WHERE rn = 1
ORDER BY FK_TS_ID, K_TC_ID