我有一列,格式如下:
Time Value
17:27 2
17:27 3
我想基于一个列获取不同的行:时间。因此,我的预期结果将是一个结果。 17:27 3或17:27 3。
T-SQL在多个列上使用不相同,而不是一个。由于时间和值的组合是唯一的,因此Distinct将返回两行(请参见下文)。
select distinct [Time], * from SAPQMDATA
会返回
Time Value
17:27 2
17:27 3
代替
Time Value
17:27 2
分组依据也似乎无效
select * from table group by [Time]
将导致:
Column 'Value' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
如何在不考虑选择查询中提供的其他列的情况下选择所有唯一的“时间”列?
如何删除重复的条目?
答案 0 :(得分:0)
ROW_NUMBER是您最好的朋友。以此作为样本数据...
time value
-------------------- -----------
17:27 2
17:27 3
11:36 9
15:14 5
15:14 6
..下面是两个可以复制/粘贴/运行的解决方案。
DECLARE @youtable TABLE ([time] VARCHAR(20), [value] INT);
INSERT @youtable VALUES ('17:27',2),('17:27',3),('11:36',9),('15:14',5),('15:14',6);
-- The most elegant way solve this
SELECT TOP (1) WITH TIES t.[time], t.[value]
FROM @youtable AS t
ORDER BY ROW_NUMBER() OVER (PARTITION BY t.[time] ORDER BY (SELECT NULL));
-- A more efficient way solve this
SELECT t.[time], t.[value]
FROM
(
SELECT t.[time], t.[value], ROW_NUMBER() OVER (PARTITION BY t.[time] ORDER BY (SELECT NULL)) AS RN
FROM @youtable AS t
) AS t
WHERE t.RN = 1;
每次返回:
time value
-------------------- -----------
11:36 9
15:14 5
17:27 2