【问题标题】:Transposing a sql query with subselects and counts转置带有子选择和计数的 sql 查询
【发布时间】: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 `


【问题讨论】:

    标签: sql count subquery amazon-athena unpivot


    【解决方案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 操作可以简化为=

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-08-14
      • 1970-01-01
      • 1970-01-01
      • 2021-03-26
      • 2023-03-12
      • 2011-01-07
      • 2013-04-04
      • 2020-10-29
      相关资源
      最近更新 更多