数据如下:
date_time | amount| user|group
---------------------
5/15/2017 6:30 | 250| a | abc
5/15/2017 6:30 | 250| a | def
5/15/2017 5:30 | 50| a |abc
5/15/2017 5:30 | 50| a |def
5/15/2017 4:30 | 50| a |abc
5/15/2017 4:30 | 50| a |def
5/15/2017 5:20 | 50| b |abc
5/15/2017 5:20 | 50| b |def
5/15/2017 5:18 | 50| b |abc
5/15/2017 5:18 | 50| b |def
期望的结果:
date_time| amount | user | group
---------------------
5/15/2017 4:30 | 50| a |abc
5/15/2017 4:30 | 50| a |def
5/15/2017 6:30 | 250| a | abc
5/15/2017 6:30 | 250| a | def
5/15/2017 5:18 | 50| b |abc
5/15/2017 5:18 | 50| b |def
具有不同值而不考虑日期时间列的结果,对于整个组,不应该对日期时间应用不同。
答案 0 :(得分:0)
您可以按行,用户,组使用row_number和分区,如下所示:
select top 1 with ties * from YourdateTable
order by row_number() over (partition by amount, [user], [group] order by amount, [user], [group])
输出:
+-------------------------+--------+------+-------+
| date_time | amount | user | group |
+-------------------------+--------+------+-------+
| 2017-05-15 05:30:00.000 | 50 | a | abc |
| 2017-05-15 04:30:00.000 | 50 | a | def |
| 2017-05-15 05:20:00.000 | 50 | b | abc |
| 2017-05-15 05:18:00.000 | 50 | b | def |
| 2017-05-15 06:30:00.000 | 250 | a | abc |
| 2017-05-15 06:30:00.000 | 250 | a | def |
+-------------------------+--------+------+-------+
答案 1 :(得分:0)
;With cte(date_time, amount,[user],[group])
AS
(
SELECT '5/15/2017 6:30' , 250, 'a' , 'abc' Union all
SELECT '5/15/2017 6:30' , 250, 'a' ,'def' Union all
SELECT '5/15/2017 5:30' , 50, 'a' ,'abc' Union all
SELECT '5/15/2017 5:30' , 50, 'a' ,'def' Union all
SELECT '5/15/2017 4:30' , 50, 'a' ,'abc' Union all
SELECT '5/15/2017 4:30' , 50, 'a' ,'def' Union all
SELECT '5/15/2017 5:20' , 50, 'b' ,'abc' Union all
SELECT '5/15/2017 5:20' , 50, 'b' ,'def' Union all
SELECT '5/15/2017 5:18' , 50, 'b' ,'abc' Union all
SELECT '5/15/2017 5:18' , 50, 'b' ,'def'
)
SELECT date_time
,amount
,[user]
,[group]
FROM (
SELECT *
,ROW_NUMBER() OVER (
PARTITION BY amount
,[user]
,[group] ORDER BY amount
,[user]
) seq
FROM cte
) dt
WHERE dt.seq = 1
ORDER BY [user]
以下是输出:
date_time amount user group
--------------------------------
5/15/2017 4:30 50 a abc
5/15/2017 5:30 50 a def
5/15/2017 6:30 250 a abc
5/15/2017 6:30 250 a def
5/15/2017 5:18 50 b abc
5/15/2017 5:18 50 b def
答案 2 :(得分:0)
SELECT MIN(date_time) AS date_time, amount, [user], [group]
FROM MyTable
GROUP BY [user], amount, [group];
根据您的上述数据,您选择的日期无关紧要,因此 MIN()用于选择不在 GROUP BY 中的日期,即不明显。< / p>