SQL Server:
给定的表有一列带有ID,一列带有整数值,一列带有值给ID的日期和时间。因此,一个ID可以有多个相应的值。
示例:
id Value datetime
---|-----|------------------------
1 | 10 | 04/03/2009 10:12:33.000
2 | 13 | 05/02/2009 11:02:03.000
1 | 20 | 10/10/2009 13:22:45.000
1 | 15 | 12/03/2010 15:12:33.000
2 | 19 | 25/05/2009 10:12:33.000
2 | 17 | 09/06/2009 17:18:45.000
如果为ID找到值20,则忽略具有相同ID的每个其他行。否则显示id的最后一个值。
结果:
id Value datetime
---|-----|------------------------
2 | 17 | 09/06/2009 17:18:45.000
答案 0 :(得分:0)
希望您使用NOT IN
或LEFT JOIN
来过滤条件。
您可以尝试以下查询:
SELECT TOP 1 *
FROM YourTable WHERE Id NOT IN (
SELECT Id FROM YourTable WHERE Value = 20)
ORDER BY Value DESC
使用数据执行示例:
DECLARE @YourTable TABLE (id INT, Value INT, datetime DATETIME)
INSERT INTO @YourTable (id, Value, datetime)
SELECT 1 , 10 , '2009-03-04 10:12:33.000' UNION
SELECT 2 , 13 , '2009-02-05 11:02:03.000' UNION
SELECT 1 , 20 , '2009-10-10 13:22:45.000' UNION
SELECT 1 , 15 , '2010-03-12 15:12:33.000' UNION
SELECT 2 , 19 , '2009-05-25 10:12:33.000' UNION
SELECT 2 , 17 , '2009-06-09 17:18:45.000'
SELECT TOP 1 *
FROM @YourTable WHERE Id NOT IN (
SELECT Id FROM @YourTable WHERE Value = 20)
ORDER BY Value DESC
答案 1 :(得分:0)
按ID分组使用ROW_NUMBER和PARTITION,并按日期时间以desc顺序选择最后一次输入值。
select id, value, datetime from (
select ROW_NUMBER() over(PARTITION by id Order by id,datetime desc) as row_rank, id, value, datetime
from tbl_1
) as A
where row_rank=1
答案 2 :(得分:0)
使用NOT EXISTS
过滤掉,并使用ROW_NUMBER
排名:
DECLARE @t TABLE ( id INT, v INT, d DATETIME )
INSERT INTO @t
VALUES ( 1, 10, '2009-03-04 10:12:33.000' ),
( 2, 13, '2009-02-05 11:02:03.000' ),
( 1, 20, '2009-10-10 13:22:45.000' ),
( 1, 15, '2010-03-12 15:12:33.000' ),
( 2, 19, '2009-05-25 10:12:33.000' ),
( 2, 17, '2009-06-09 17:18:45.000' );
WITH cte
AS ( SELECT * ,
ROW_NUMBER() OVER ( PARTITION BY id ORDER BY d DESC ) AS rn
FROM @t t
WHERE NOT EXISTS ( SELECT *
FROM @t
WHERE id = t.id
AND v = 20 )
)
SELECT *
FROM cte
WHERE rn = 1
答案 3 :(得分:0)
SELECT Top 1 *
FROM @YourTable
Group by id, Value, datetime
Having Value<20
ORDER BY Value DESC