向现有子查询引入简单计数子查询

时间:2019-02-08 12:19:49

标签: sql sqlite

我正在创建一个连接到SQLite数据库的简单图像浏览器。在浏览器中,相似的图像被分组为一个事件,并且每个图像都带有一些标签

有人帮助我在下面构造了这个非常有用的查询。它包含5个随机标记作为示例:

SELECT * 
FROM 
    (SELECT 
         t.EventId,
         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 
         name IN ('necktie', 'shirt', 'suit', 'man', 'male') 
     GROUP BY 
         t.EventId) 
ORDER BY 
    COUNT(*) DESC

这将返回每个事件中出现的每个标签(列称为“名称”)的数量。但是,现在我还需要事件的大小(事件中唯一图像ID的数量),可以通过以下查询来完成:

SELECT EventId, COUNT(DISTINCT ImageId) 
FROM TagsMSCV 
GROUP BY EventId 

但是我不知道如何将这种语法引入上面的子查询中?如果我将其放在t.EventId旁边,则仅在使用5个不正确标签进行标记的情况下才对图像ID进行计数。我需要事件中的总唯一图像ID。

1 个答案:

答案 0 :(得分:1)

首先,您的子查询不是必需的。其次,您可以使用条件COUNT(DISTINCT)

SELECT t.EventId,
        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 
        COUNT(DISTINCT CASE WHEN name = 'necktie' THEN imageid END) as necktie_images,
        COUNT(DISTINCT CASE WHEN name = 'shirt' THEN imageid END) as shirt_images,
        COUNT(DISTINCT CASE WHEN name = 'suit' THEN imageid END) as suit_images,
        COUNT(DISTINCT CASE WHEN name = 'man' THEN imageid END) as man_images,
        COUNT(DISTINCT CASE WHEN name = 'male' THEN imageid END) as male_images
FROM TagsMSCV t
WHERE name IN ('necktie', 'shirt', 'suit', 'man', 'male')
GROUP BY t.EventId 

编辑:

如果您想要一个事件的全部不同图像,则不需要条件逻辑。只需使用:

COUNT(DISTINCT imageid) as total_images,

并删除WHERE子句。