简体   繁体   中英

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. 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). This query obviously doesnt work since the tblKey is not in the subquery, but I cant figure out a way to work around this.

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:

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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