sql—如何选择表中的所有列,并在多个列上使用distinct

kiayqfof  于 2021-07-26  发布在  Java
关注(0)|答案(1)|浏览(421)

我看到过一些类似的帖子,但我发现没有什么是真正有意义的或我尝试过的作品。实际上,我需要在3列上选择distinct,但返回表中的所有列。到目前为止,这就是我所拥有的:

SELECT *
FROM tbl1
WHERE tblKey IN (SELECT DISTINCT personKey, contentkey, EmailKey
                                FROM tbl1
                                WHERE (Application = 'website' OR Application = 
                                'connect') AND
                                (contentKey IN (12, 13, 14, 16, 17, 18 , 19)) AND
                                (channelKey = 1))

子查询中的where语句是因为这只应应用于where子句的内容(很明显,但要确保知道我没有试图删除where子句中的重复项)。这个查询显然不起作用,因为tblkey不在子查询中,但是我想不出解决这个问题的方法。

mrphzbgm

mrphzbgm1#

如果希望每个键组合有一个示例行,那么代码将使用聚合函数:

SELECT *
FROM tbl1
WHERE tblKey IN (SELECT MAX(tblKey) 
                 FROM tbl1
                 WHERE Application IN ('website', 'connect') AND
                       contentKey IN (12, 13, 14, 16, 17, 18 , 19) AND
                       channelKey = 1
                 GROUP BY personKey, contentkey, EmailKey
                );

我确实认为使用窗口函数来表达这一点更为常见:

SELECT t.* 
FROM (SELECT t.*
             ROW_NUMBER() OVER (PARTITION BY personKey, contentkey, EmailKey ORDER BY (SELECT NULL)) as seqnum
      FROM tbl1 t
      WHERE Application IN ('website', 'connect') AND
           contentKey IN (12, 13, 14, 16, 17, 18 , 19) AND
           channelKey = 1
     ) t
WHERE seqnum = 1;

相关问题