Student_No Modified_ON StatusID
1234 1 Nov 2017 1
1234 2 Nov 2017 2
1235 1 Nov 2017 1
1235 2 Nov 2017 1
1235 3 Nov 2017 3
1236 1 Nov 2017 1
1236 3 Nov 2017 2
1237 3 Nov 2017 3
预期的O / p
Student_No Modified_ON StatusID
1234 2 Nov 2017 2
1236 3 Nov 2017 2
我需要所有最新(最高日期)记录,其中StatusID从1变为2
答案 0 :(得分:0)
根据您的输出,您需要group by
max
功能聚合
SELECT Student_No,
MAX(Modified_ON) [Modified_ON],
MAX(StatusID) [StatusID]
FROM
(
SELECT *
FROM <TABLE>
WHERE StatusID = 2
AND Student_No IN
(
SELECT Student_No
FROM <TABLE>
WHERE StatusID = 1
)
) AA
GROUP BY Student_No;
以上SQL脚本将返回
Student_No Modified_ON StatusID
1234 2 Nov 2017 2
1236 3 Nov 2017 2
答案 1 :(得分:0)
使用多个查询和if-else子句执行此操作:
SELECT (
CASE WHEN ( (
SELECT StatusID
FROM students
ORDER BY `Modified_ON` DESC
LIMIT 1
) = 1)
THEN
( SELECT Student_No
FROM students
ORDER BY `Modified_ON` DESC
LIMIT 1 )
ELSE (
SELECT Student_No
FROM students
WHERE StatusID = 2 and Student_No in (
SELECT Student_No
FROM students
WHERE StatusID = 1
)
ORDER BY `Modified_ON` DESC LIMIT 1
)
END )
FROM students
请参阅mysql-fiddle:http://sqlfiddle.com/#!9/c601d9/2
答案 2 :(得分:0)
使用窗口函数我们得到预期的结果
;With cte(Student_No, Modified_ON, StatusID )
AS
(
SELECT 1234,'1 Nov 2017', 1 UNION ALL
SELECT 1234,'2 Nov 2017', 2 UNION ALL
SELECT 1235,'1 Nov 2017', 1 UNION ALL
SELECT 1235,'2 Nov 2017', 1 UNION ALL
SELECT 1235,'3 Nov 2017', 3 UNION ALL
SELECT 1236,'1 Nov 2017', 1 UNION ALL
SELECT 1236,'3 Nov 2017', 2 UNION ALL
SELECT 1237,'3 Nov 2017', 3
)
SELECT Student_no,
Modified_on,
Statusid
FROM (SELECT Student_no,
Max(Modified_on)
OVER(
partition BY Student_no
ORDER BY Modified_on DESC) Modified_ON,
Statusid
FROM
Cte
WHERE Statusid IN( 1, 2 ))dt2
WHERE dt2.Statusid = 2
结果
Student_no Modified_on Statusid
----------------------------------
1234 2 Nov 2017 2
1236 3 Nov 2017 2
答案 3 :(得分:0)
我还有代码但格式不正确,因此Stackflow不允许它。您可以考虑我已实施的以下逻辑。
逻辑:通过唯一编号,Status_Id和按日期排序描述创建SR编号
使用所需的where子句
选择ROw_Number和Rank_Number以选择上面的数据