我该如何在BigQuery中旋转该查询

时间:2018-08-10 10:48:16

标签: google-bigquery

我在Bigquery中有一个查询,我想在“项目站点名称”和“研究ID”上显示输出。

这是代码:

SELECT
    Project_Site_Name,
    NIHR_Portfolio_Study_ID,
    CASE WHEN (Recruitment_Year = '2017/18')
         THEN COUNT(Patient_Local_Number) END AS rec1718,
    CASE WHEN (Recruitment_Year = '2018/19')
         THEN COUNT(Patient_Local_Number) END AS rec1819
FROM `fourth-jigsaw-118116.Partners.PARData`
WHERE
    NIHR_Portfolio_Study_ID = 1358 AND
    Recruitment_Year IN ('2017/18', '2018/19')
GROUP BY
    Project_Site_Name,
    NIHR_Portfolio_Study_ID,
    Recruitment_Year

当前,这是输出:

enter image description here

我希望它看起来像这样:

enter image description here

我一直在寻找解决方案已有一段时间,我认为这可能与将聚合嵌套在子查询中有关,但这与我所能做到的差不多。有什么建议吗?

最美好的祝愿

戴夫

1 个答案:

答案 0 :(得分:4)

如果您想根据招聘年份来划分结果列,则不应按该列进行分组。相反,请使用条件汇总来确定每个招聘年的人数。

SELECT
    Project_Site_Name,
    NIHR_Portfolio_Study_ID,
    COUNT(CASE WHEN Recruitment_Year = '2017/18' THEN 1 END) AS rec1718,
    COUNT(CASE WHEN Recruitment_Year = '2018/19' THEN 1 END) AS rec1819
FROM fourth-jigsaw-118116.Partners.PARData
WHERE
    NIHR_Portfolio_Study_ID = 1358 AND
    Recruitment_Year IN ('2017/18', '2018/19')
GROUP BY
    Project_Site_Name,
    NIHR_Portfolio_Study_ID;