Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql question about select - trivial?

Tags:

sql

sql-server

seems trivial, but can't find solution -

i need to write query which gets me persons based on values of attributes (e.g. get me persons which have attr '1' AND '2' AND '3')

*clarification: querying could be done on more than three value of attributes - it will be user selected - from 0 to n values, but i don't expect more than 7 values... *

-- tsql script --------------
create table ##temp (person char(1), attr char(1)  );

-- can be 1..n persons and 1..n attributes
insert into ##temp VALUES 
('A','1'),
('A','2'),
('B','1'),
('C','2');

-- sample: get all persons which have attribute 1 AND 2
-- sample: result should be 'A' only

drop table ##temp
-- tsql script -----------------

thanks for helping, hh

like image 241
hitchhiker Avatar asked Aug 24 '26 18:08

hitchhiker


2 Answers

You could use a GROUP BYwith a HAVING COUNT(DISTINCT)clause.

SQL Statement

SELECT  person
FROM    ##temp
WHERE   attr IN ('1', '2')
GROUP BY 
        person
HAVING  COUNT(DISTINCT attr) = 2

Following statement will always outperform the COUNT(DISTINCT) but will yield incorrect results if duplicates are present. please note that the outperformance might not be measurable.

SELECT  person
FROM    ##temp
WHERE   attr IN ('1', '2')
GROUP BY 
        person
HAVING  COUNT(*) = 2
like image 61
Lieven Keersmaekers Avatar answered Aug 29 '26 18:08

Lieven Keersmaekers


normal you have 1 table for person where every person is listed singletime, and a second table with the atributes

select person from (
  select person, count(person) as cnt from ##temp where attr in (1,2,3) group by person
) where cnt = 3

this should do the work

but in your testing table was only attr 1 and 2 ... so this won't show any results

select person from (
  select person, count(person) as cnt from ##temp where attr in (1,2) group by person
) where cnt = 2

will show you A

like image 25
f1r3Ph03n1xX Avatar answered Aug 29 '26 17:08

f1r3Ph03n1xX



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!