繁体   English   中英

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

[英]Combining two aggregate queries into one

对于某些情况,我正在制作一个连接到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

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

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

您应该在一个查询中完成全部操作:

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;

您需要两次聚合才能获得有关标签计数的信息。 无需添加更多的聚合和联接到查询。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM