简体   繁体   English

如何 select 表中的所有列与多列不同

[英]How to select all columns in table with Distinct on multiple columns

I've seen some posts similar to this, but nothing I have found really makes sense or works that I have tried.我看过一些与此类似的帖子,但我发现没有任何东西真正有意义或我尝试过的作品。 Essentially I need to select distinct on 3 columns, but return all the columns in the table.本质上我需要 select 在 3 列上不同,但返回表中的所有列。 So far this is what I have:到目前为止,这就是我所拥有的:

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))

The where statement in the subquery is because This only should apply to the content that is true to the where clause (obviously, but just making sure its known that Im not trying to remove duplicates in the where clause).子查询中的 where 语句是因为这仅适用于 where 子句的内容(显然,但只是确保知道我没有尝试删除 where 子句中的重复项)。 This query obviously doesnt work since the tblKey is not in the subquery, but I cant figure out a way to work around this.这个查询显然不起作用,因为 tblKey 不在子查询中,但我想不出解决这个问题的方法。

If you want one sample row for each combination of keys, then your code would work with aggregation functions:如果您希望每个键组合都有一个示例行,那么您的代码将使用聚合函数:

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
                );

I do think that it would be more common to express this using window functions:我确实认为使用 window 函数来表达这一点会更常见:

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM