如何从表中选择数据以转置或交叉表方式输出?

Posted

技术标签:

【中文标题】如何从表中选择数据以转置或交叉表方式输出?【英文标题】:How to select data from table to get output in transpose or crosstab manner? 【发布时间】:2017-12-29 21:53:11 【问题描述】:

我有一个具有以下值的表格报告数据:

 reportdata       memberCount     monthname     year
Assigned user        588           February     2017
Assigned user        2             January      2017
Assigned user        22            May          2017
FHD                  571           February     2017
FHD                  15            May          2017
ICM                  1             May          2017
sortingCompleted     1             February     2017
sortingCompleted     2             May          2017

我想要这样的输出:

   reportdata           January   February      May
    Assigned user           2       588          22
       FHD                  0       571          15
       ICM                  0        0            1
   sortingCompleted         0        1            2

我尝试过以下查询:

select d.reportdata,
CASE WHEN d.monthname='January' THEN d.MemberCount END AS January,
CASE WHEN d.monthname='February' THEN d.MemberCount END AS February,  
CASE WHEN d.monthname='May' THEN d.MemberCount END AS May from
(
select reportdata, memberCount,monthname
from cme_report where year='2017'
) as d

请建议获得预期输出的方法。提前感谢。

【问题讨论】:

【参考方案1】:

您可以尝试以下方法:

SELECT
    reportdata,
    SUM(CASE WHEN (monthname = 'January') THEN memberCount ELSE 0 END) AS 'January',
    SUM(CASE WHEN (monthname = 'February') THEN memberCount ELSE 0 END) AS 'February',
    SUM(CASE WHEN (monthname = 'May') THEN memberCount ELSE 0 END) AS 'May', 
FROM reportdata
WHERE year = '2017'
GROUP BY reportdata

【讨论】:

非常感谢@Sebastian Brosch,一切正常......非常感谢......

以上是关于如何从表中选择数据以转置或交叉表方式输出?的主要内容,如果未能解决你的问题,请参考以下文章

PostgreSQL 交叉表转置行到列

如何在 Postgresql 交叉表中获取动态列数

如何使用spss进行交叉列联表分析

如何在 HIVE hql 中添加两个计数?

我们如何在交叉表中执行以下任务?

如何在交叉表中显示行总数和列总数?