sql:选择所有具有最大值和where条件的行

rnmwe5a2  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(425)

我有一张这样的table:

id  data    version rulecode
---------------------------
a1  1           100     x1
a2  1           100     x1
a1  1           200     x2
a4  2           500     x2
a7  2           200     x1
a6  2           500     x1
a7  2           500     x2
a8  2           150     x2
a9  3           120     x1
a10 3           130     x2
a10 3           120     x1
a12 3           130     x2
a13 3           130     x1
a14 3           110     x2
a15 3           110     x1
a16 4           220     x1
a17 4           230     x2
a18 4           240     x2
a19 4           240     x1
..........................
..........................

现在我只想要那些最大 version 以及 data 值为(1、2和4)
当我试着 dense_rank() ,我只得到那些 1 价值来自 data 列:

SELECT * FROM 
(SELECT *, dense_rank() OVER (ORDER BY version desc) as col
FROM public.table_name WHERE data in (1,2,4))x
WHERE x.col=1

输出:

id  data    version rulecode
---------------------------
a1  1           200     x2

我的预期产出:

id  data    version rulecode
a1  1           200     x2
a4  2           500     x2
a6  2           500     x1
a8  2           500     x2
a18 4           240     x2
a19 4           240     x1

注:值 data 纵队一直到百万。
有人能帮我得到预期的结果吗?

elcex8rz

elcex8rz1#

你好像想要一个 PARTITION BY :

SELECT * 
FROM (SELECT *,
             DENSE_RANK() OVER (PARTITION BY data ORDER BY version desc) as seqnum
      FROM public.table_name
      WHERE data in (1, 2, 4)
     ) x
WHERE x.seqnum = 1
w1e3prcc

w1e3prcc2#

使用分析函数:

WITH cte AS (
    SELECT *, MAX(version) OVER (PARTITION BY data) max_version
    FROM yourTable
)

SELECT id, data, version, rulecode
FROM cte
WHERE version = max_version AND data IN (1, 2, 4);

注意,我们还可以过滤 data cte中的值。我将保持原样,以便对你的问题有一个全面的解决办法。

相关问题