一尘不染

SQL查询将列数转换为行数

sql

我有一个类似于以下表格的表格,其中显示了类型计数。我需要并且一直试图将数据显示为1列和7行,但是…没有成功。


| col types      | win2k | winxp | win2k3 | vista | win7 | win8 | win8.1

|


| count of types |  2365 | 65655 | 422445 | 4822  | 482  | 2331 | 485323

|


Select 
count(case when col1 ~* '5.0.2195' then 1 else null end) as Win2k,
count(case when col1 ~* '5.1.2600' then 1 else null end) as WinXP, 
count(case when col1 ~* '5.2.3790' then 1 else null end) as W2k3,
count(case when (col1 ~* '6.0.6000'
    or col1 ~* '6.0.6001' or col1 ~* '6.0.6002') 
    then 1 else null end) as Vista,
count(case when (col1 ~* '6.1.7600'
    or col1 ~* '6.1.7601')
    then 1 else null end) as Win7,
count(case when col1 ~* '6.2.9200' then 1 else null end) as Win8,
count(case when (col1 ~* '6.3.9200'
    or col1 ~* '6.3.9600')
    then 1 else null end) as "Win8.1"
From col1

理想情况下,它看起来像这样:

___________________
| types  | count  |
-------------------
| win2k  | 2365   |
| winxp  | 65655  |
| win2k3 | 422445 |
| vista  | 4822   |
| win7   | 482    |
| win8   | 2331   |
| win8.1 | 485323 |
-------------------

笔记:

  • 我正在将Postgresql 9.3与PGADMIN III一起使用
  • 我无法创建任何自定义函数
  • 是否有更多的列可以使这项工作无关紧要

阅读 179

收藏
2021-05-16

共1个答案

一尘不染

以GROUP BY为目标,更容易进行此类查询,如下所示:

Select 
case when profile.foo ~* '5.0.2195' then 'Win2k'
     when profile.foo ~* '5.1.2600' then 'WinXP' 
     when profile.foo ~* '5.2.3790' then 'W2k3'
     when (profile.foo ~* '6.0.6000'
        or profile.foo ~* '6.0.6001'
        or profile.foo ~* '6.0.6002') 
        then 'Vista'
     when (profile.foo ~* '6.1.7600'
        or profile.foo ~* '6.1.7601')
        then 'Win7'
     when profile.foo ~* '6.2.9200' then 'Win8'
     when (profile.foo ~* '6.3.9200'
        or profile.foo ~* '6.3.9600')
        then 'Win8.1' ELSE 'Other' END as type,
     count(*) as cnt
From profile
GROUP BY 1

如下所述,此查询适用于互斥情况,即当profile.foo包含一个代表每行一个操作系统的值时

2021-05-16