简体   繁体   中英

SQL Filter rows based on multiple distinct values of a column

Given the following table

DECLARE @YourTable TABLE (id int, PLU int, Siteid int, description varchar(50))

INSERT @YourTable VALUES (1, 8972, 2, 'Beer')
INSERT @YourTable VALUES (2, 8972, 3, 'cider')
INSERT @YourTable VALUES (3, 8972, 4, 'Beer')
INSERT @YourTable VALUES (4, 8973, 2, 'Vodka')
INSERT @YourTable VALUES (5, 8973, 3, 'Vodka')
INSERT @YourTable VALUES (6, 8973, 4, 'Vodka')

I trying to write a query that would give me all rows that have multiple distinct values for a given description value against a plu.

So in the example above I would want to return rows 1,2,3 as they have both a 'cider' value and a 'beer' value for a plu of '8972'.

I thought 'GROUP BY' and 'HAVING' was the way to go but I can't seem to get it to work correctly.

SELECT P.PLU, P.Description 
FROM @YourTable P
GROUP BY P.PLU, P.Description
HAVING COUNT(DISTINCT(P.DESCRIPTION)) > 1

Any help appreciated.

You shouldn't GROUP BY the description if you are doing a DISTINCT COUNT on it (then it will always be just 1). Try something like this:

SELECT P2.PLU, P2.Description
FROM @YourTable P2 
WHERE P2.PLU in (
      SELECT P.PLU 
      FROM @YourTable P
      GROUP BY P.PLU
      HAVING COUNT(DISTINCT(P.DESCRIPTION)) > 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