将两个汇总查询合并为一个

时间:2019-02-08 16:37:20

标签: sql sqlite

对于某些情况,我正在制作一个连接到SQLite数据库的图像浏览器。在浏览器中,相似的图像被分组为一个事件(EventId),并且每个图像(MicrosoftId)都带有一些标记(名称)

我在同一张表( TagsMSCV )上有这两个查询,但是提取了不同的信息。最终,我需要在浏览器中合并信息,因此,如果可以合并这两个查询(也许使用JOIN?),对我来说将更快,更方便。这些查询的两个结果共享EventId列。

第一个查询():

SELECT EventId as 'event', count(*) as 'size',
    SUM(case when tag_count = 1 then 1 else 0 end) as '1',
    SUM(case when tag_count = 2 then 1 else 0 end) as '2',
    SUM(case when tag_count = 3 then 1 else 0 end) as '3'
FROM (SELECT EventId, MicrosoftId,
SUM(case when name in ('indoor', 'cluttered', 'screen') then 1 else 0 end) as tag_count 
FROM TagsMSCV GROUP BY EventId, MicrosoftId) TagsMSCV
GROUP BY EventId ORDER BY 3 DESC, 2 DESC, 1 DESC

第二次查询

SELECT EventId,
    SUM(CASE WHEN name = 'indoor' THEN 1 ELSE 0 END) as indoor,
    SUM(CASE WHEN name = 'cluttered' THEN 1 ELSE 0 END) as cluttered,
    SUM(CASE WHEN name = 'screen' THEN 1 ELSE 0 END) as screen
FROM TagsMSCV WHERE name IN ('indoor', 'cluttered', 'screen')
GROUP BY EventId

在两个查询中都可以看到,我正在输入标签“领带”,“男人”,“男性”,并获取不同的信息。

SQL小提琴在这里:https://www.db-fiddle.com/f/f8WNimjmZAj1XXeCj4PHB8/3

2 个答案:

答案 0 :(得分:1)

您可以使用内部联接子查询

SELECT TagsMSCV.EventId as 'event', count(*) as 'size',
    SUM(case when tag_count = 1 then 1 else 0 end) as '1',
    SUM(case when tag_count = 2 then 1 else 0 end) as '2',
    SUM(case when tag_count = 3 then 1 else 0 end) as '3',
    t.necktie, 
    t.man,
    t.male
FROM (
  SELECT EventId, MicrosoftId,
  SUM(case when name in ('necktie' 'man', 'male') then 1 else 0 end) as tag_count 
  FROM TagsMSCV GROUP BY EventId, MicrosoftId
) TagsMSCV
INNER JOIN (
  SELECT EventId,
      SUM(CASE WHEN name = 'necktie' THEN 1 ELSE 0 END) as necktie,
      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 WHERE name IN ('necktie' 'man', 'male')
  GROUP BY EventId
) t on t.EventId = TagsMSCV.EventId 
GROUP BY TagsMSCV.EventId 
ORDER BY 3 DESC, 2 DESC, 1 DESC

答案 1 :(得分:1)

您应该在一个查询中完成所有操作:

SELECT EventId as event, count(*) as size,
       SUM(case when (indoor + cluttered + screen) = 1 then 1 else 0 end) as tc_1,
       SUM(case when (indoor + cluttered + screen) = 2 then 1 else 0 end) as tc_2,
       SUM(case when (indoor + cluttered + screen) = 3 then 1 else 0 end) as tc_3,
       SUM(indoor) as indoor,
       SUM(cluttered) as cluttered,
       SUM(screen) as screen
FROM (SELECT EventId, MicrosoftId,
             SUM(CASE WHEN name = 'indoor' THEN 1 ELSE 0 END) as indoor,
             SUM(CASE WHEN name = 'cluttered' THEN 1 ELSE 0 END) as cluttered,
             SUM(CASE WHEN name = 'screen' THEN 1 ELSE 0 END) as screen
      FROM TagsMSCV
      GROUP BY EventId, MicrosoftId
     ) TagsMSCV
GROUP BY EventId
ORDER BY 3 DESC, 2 DESC, 1 DESC;

您需要两次汇总以获取有关标签计数的信息。无需添加更多聚合和联接。