简体   繁体   中英

SQL Query Multiple conditions on a column (On same Table)

I have the following question and here is an example for better understanding.

Assume i have a table like this:

在此处输入图片说明

I want to get the Distinct Ids(Not Nulls), that have Spec 2 and they don't have spec 5 from Spec Column.

An expected result would be something like this:

Expected Result:

在此处输入图片说明

Is it something like left-join? Unfortunately I am not getting the desired result through my queries.

use exists and not exists

select camid from table_name t1
where not exists ( select 1 from table_name t2 where t1.camid=t2.camid
                   and Specs= 'Spec 5')
 and exists ( select 1 from table_name t2 where t1.camid=t2.camid 
                                   and Specs= 'Spec 2')

Try this below script-

SELECT DISTINCT Cam_ID 
FROM your_table
WHERE Cam_ID NOT IN
(
    SELECT DISTINCT Cam_ID 
    FROM your_table
    WHERE Specs = 'Specs 5'
)
AND Specs = 'Specs 2'
AND Cam_ID IS NOT NULL
SELECT Cam_ID 
FROM source_table
WHERE Cam_ID IS NOT NULL -- if Cam_ID cannot be zero then simply 
                         -- WHERE Cam_ID
GROUP BY Cam_ID
HAVING  SUM(Specs = 'Specs 2') -- at least one 'Specs 2'
   AND !SUM(Specs = 'Specs 5') -- and none 'Specs 5'

Below SQL Script should give you the required output.

SELECT CamId FROM (
SELECT t.CamId,
STUFF((
SELECT  ',' + Specs FROM
(SELECT t1.Specs FROM test_table as t1 
WHERE t1.CamId = t.CamId) AS T 
FOR XML PATH('')
),1,1,'') AS specs
FROM test_table AS t
WHERE CamId IS NOT NULL
GROUP BY CamId) AS t5
where t5.specs LIKE '%Specs 2%'
AND t5.specs NOT LIKE '%Specs 5%'
SELECT Cam_Id 
FROM table_one t1 
WHERE
    NOT EXISTS ( SELECT 1 FROM table_one t2 WHERE t1.Cam_Id = t2.Cam_Id AND Specs = 'Spec 5' ) 
    AND EXISTS ( SELECT 1 FROM table_one t2 WHERE t1.Cam_Id = t2.Cam_Id AND Specs = 'Spec 2' ) 
GROUP BY Cam_Id

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