转置带有子选择和计数的 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 BYORDER BY 子句的意义,而您的输出表明它们返回一行 - 我删除了它们

您的大部分IN 操作可以简化为=

正确缩进的代码更容易编写和阅读!

【讨论】:

以上是关于转置带有子选择和计数的 sql 查询的主要内容,如果未能解决你的问题,请参考以下文章

如何提高 SQL Server 查询的性能以选择具有值的行不在子查询中的一次计数

如何将带有子选择的 SQL 查询转换为 MDX 查询?

带有子查询排除的 SQL 选择字段

带有联接、计数和位置的 SQL 查询

根据条件选择查询和计数

SQL 从带有子查询的多个表中选择数据(包括来自内部连接的数据)错误:1242