简体   繁体   中英

Trying to introduce a simple new condition to a JOIN query

I am using SQLite and I had someone help me construct this JOIN query which works quite well, but now I need to add another condition but I am having trouble introducing it to the query without it breaking.

In both tables used in the JOIN there is a column called EventId and I want to introduce the simple condition...

WHERE EventId = 123456

Below you can see a working example of the query itself along with two comments where I have tried to introduce the new condition and failed (because I'm bad at SQL).

SELECT t.MicrosoftId, 
    SUM(CASE WHEN name = 'necktie' THEN 1 ELSE 0 END) as 'necktie',
    SUM(CASE WHEN name = 'shirt' THEN 1 ELSE 0 END) as 'shirt',
    SUM(CASE WHEN name = 'suit' THEN 1 ELSE 0 END) as 'suit',
    SUM(CASE WHEN name = 'man' THEN 1 ELSE 0 END) as 'man',
    SUM(CASE WHEN name = 'male' THEN 1 ELSE 0 END) as 'male' 
FROM TagsMSCV t 
        /* <---- WHERE t.EventId = 123456 (fails here...) */
LEFT JOIN 
(SELECT i.MicrosoftId
FROM Images i 
GROUP BY i.MicrosoftId) i 
ON i.MicrosoftId = t.MicrosoftId 
WHERE t.name IN ('necktie','shirt','suit','man','male') 
        /* <---- AND WHERE t.EventId = 123456 (fails here too...) */
GROUP BY t.MicrosoftId

try like below

select t1.* from   ( SELECT t.MicrosoftId, 
        SUM(CASE WHEN name = 'necktie' THEN 1 ELSE 0 END) as 'necktie',
        SUM(CASE WHEN name = 'shirt' THEN 1 ELSE 0 END) as 'shirt',
        SUM(CASE WHEN name = 'suit' THEN 1 ELSE 0 END) as 'suit',
        SUM(CASE WHEN name = 'man' THEN 1 ELSE 0 END) as 'man',
        SUM(CASE WHEN name = 'male' THEN 1 ELSE 0 END) as 'male' 
    FROM TagsMSCV t WHERE t.EventId = 123456 
  and name IN ('necktie','shirt','suit','man','male') group by t.MicrosoftId 
  ) t1

You did mistake to create subquery and as 2nd subquery no need group by as there no aggregate function used

It should be in WHERE section, but without second WHERE keyword:

SELECT t.MicrosoftId, 
    SUM(CASE WHEN name = 'necktie' THEN 1 ELSE 0 END) as 'necktie',
    SUM(CASE WHEN name = 'shirt' THEN 1 ELSE 0 END) as 'shirt',
    SUM(CASE WHEN name = 'suit' THEN 1 ELSE 0 END) as 'suit',
    SUM(CASE WHEN name = 'man' THEN 1 ELSE 0 END) as 'man',
    SUM(CASE WHEN name = 'male' THEN 1 ELSE 0 END) as 'male' 
FROM TagsMSCV t 
LEFT JOIN 
(SELECT i.MicrosoftId
FROM Images i 
GROUP BY i.MicrosoftId) i 
ON i.MicrosoftId = t.MicrosoftId 
WHERE t.name IN ('necktie','shirt','suit','man','male') 
AND t.EventId = 123456
GROUP BY t.MicrosoftId

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