转置带有子选择和计数的 sql 查询
Posted
技术标签:
【中文标题】转置带有子选择和计数的 sql 查询【英文标题】:Transposing a sql query with subselects and counts 【发布时间】:2020-09-19 01:32:15 【问题描述】:我需要转置此查询的结果(结果如图所示)以根据结果绘制直方图。 很快将索引 1 的行设为列,并将 main_objective、new_milestone、main_objective、main_milestone、main_kr 设为行。 https://i.stack.imgur.com/d2nn0.png
SELECT A.main_objective,
A.new_milestone,
A.main_objective,
A.main_milestone,
A.main_kr FROM
(SELECT
(SELECT count(label)
FROM "roads-fe-db"."track"
WHERE key IN ('newarea_option_clicked')
AND label LIKE '%option.[object_object],_objective%'
GROUP BY label
ORDER BY count(*) desc) AS new_objective,
(SELECT count(label)
FROM "roads-fe-db"."track"
WHERE key IN ('newarea_option_clicked')
AND label LIKE '%option.[object_object],_milestones%'
GROUP BY label
ORDER BY count(*) desc) AS new_milestone,
(SELECT count(label)
FROM "roads-fe-db"."track"
WHERE key IN ('okrboard_newobjective_clicked')
GROUP BY label
ORDER BY count(*) desc) AS main_objective,
(SELECT count(label)
FROM "roads-fe-db"."track"
WHERE key IN ('milestoneboard_newmilestone_clicked')) AS main_milestone,
(SELECT count(label)FROM "roads-fe-db"."track"
WHERE label LIKE '%+_new_key_result%') AS main_kr )A `
【问题讨论】:
【参考方案1】:最简单的方法可能是union all
您现有的子查询:
SELECT 'new_objective' metric, count(label) value
FROM "roads-fe-db"."track"
WHERE key = 'newarea_option_clicked' AND label LIKE '%option.[object_object],_objective%'
UNION ALL
SELECT 'new_milestone', count(label)
FROM "roads-fe-db"."track"
WHERE key = 'newarea_option_clicked' AND label LIKE '%option.[object_object],_milestones%'
UNION ALL
SELECT 'main_objective', count(label)
FROM "roads-fe-db"."track"
WHERE key = 'okrboard_newobjective_clicked'
UNION ALL
SELECT 'main_milestone', count(label)
FROM "roads-fe-db"."track"
WHERE key = 'milestoneboard_newmilestone_clicked'
UNION ALL
SELECT 'main_kr', count(label)
FROM "roads-fe-db"."track"
WHERE label LIKE '%+_new_key_result%'
注意事项:
我没有看到子查询中 GROUP BY
和 ORDER BY
子句的意义,而您的输出表明它们返回一行 - 我删除了它们
您的大部分IN
操作可以简化为=
正确缩进的代码更容易编写和阅读!
【讨论】:
以上是关于转置带有子选择和计数的 sql 查询的主要内容,如果未能解决你的问题,请参考以下文章