我尝试选择max(date_added)支付方面的行,只选择col_a和col_b中的重复值,其中 log_id 是唯一的。我已经看过使用DISTINCT ON并使用窗口函数的解决方案,但是我无法正确获取语法以获得我想要的结果。
从此表中:
+--------+-------+-------+-------+-------+-------+-------------------------+ | log_id | col_a | col_b | col_c | col_d | col_e | date_added | +--------+-------+-------+-------+-------+-------+-------------------------+ | 1 | ACME | West | 14 | 27 | A | 2016-01-01 12:45:00.453 | | 2 | ACME | West | 17 | 31 | A | 2016-01-02 07:33:24.551 | | 3 | ACME | East | 13 | 27 | B | 2016-01-01 11:43:21.223 | | 4 | ACME | East | 17 | 28 | A | 2016-01-03 09:15:50.113 | +--------+-------+-------+-------+-------+-------+-------------------------+
我该如何归还:
+--------+-------+-------+-------+-------+-------+-------------------------+ | log_id | col_a | col_b | col_c | col_d | col_e | date_added | +--------+-------+-------+-------+-------+-------+-------------------------+ | 2 | ACME | West | 17 | 31 | A | 2016-01-02 07:33:24.551 | | 4 | ACME | East | 17 | 28 | A | 2016-01-03 09:15:50.113 | +--------+-------+-------+-------+-------+-------+-------------------------+
答案 0 :(得分:0)
一种方法是使用窗口函数......类似......
set my variable to 4
这样做是按照添加日期的降序为每个col_A和col_B分组(将每个A,b组的行号重置为1)分配行号,然后仅返回行号为1的记录(拥有最长日期)
或在窗口函数之前...我们在每个col_a和Col_B组中获取一组最大日期数据,然后连接回基本集以限制数据。
with cte as (SELECTlog_id,col_a,col_b,col_c,col_d, col_e, date_added,
row_number() over (partition by col_A, col_B order by date_added desc) rn
FROM tableName )
SELECT log_id,col_a,col_b,col_c,col_d,col_e,date_added
FROM cte
WHERE rn = 1;
答案 1 :(得分:0)
使用distinct on
很简单:
select distinct on (col_a, col_b)
*
from
yourtable
order by
col_a, col_b, -- columns from `distinct on` should be in the `order by` clause
-- and here is a max value of date_added for every distinct (col_a, col_b) pairs
-- because of descending order
date_added desc;