【发布时间】:2014-09-11 22:18:13
【问题描述】:
我有一个如下所示的表格,其中显示了类型的数量。我需要并且一直在尝试将数据显示为 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 | -------------------
注意事项:
- 我正在使用带有 PGADMIN III 的 Postgresql 9.3
- 我无法创建任何自定义函数
- 如果有更多的列来完成这项工作并不重要
【问题讨论】:
-
unpivot and PostgreSQL 的可能重复项
-
我认为 Bulat 是正确的,你想要一个与 postgresql.org/docs/9.1/static/tablefunc.html 相反的(未)数据透视表
-
Bulat,我在发布之前查看并尝试了该参考资料,虽然它可能看起来相似,但它具有不适用的不同表/数据结构。我的单行是聚合数据,即使不是不可能,也使得 unpivot 非常困难。
-
当然可以。您提出的查询是非法且令人困惑的,因此很难说什么最适合您。
profile.foo在您的查询上下文中不是合法的列名。请修复问题。您可以提供表定义和一些示例值来澄清。 -
发布的第一个问题...仍在学习中。
标签: sql postgresql unpivot unnest