sql - 聚合函数选择
问题描述
有一个 tbl_Regist 表:
| ID | CODE | VAL |
+----+--------+-----------+
| 95 | numVz | 06 |
| 95 | prevVz | 84605898 |
| 95 | ndatVz | 10.10.10 |
| 95 | numVz | 06 |
| 95 | prevVz | 14666641 |
| 95 | ndatVz | 11.11.11 |
| 95 | numVz | 06 |
| 95 | prevVz | 84605898 |
| 95 | ndatVz | 12.12.12 |
我需要在这个视图中获取数据:
| ID | numVz | prevVz | ndatVz |
+----|-------+----------+----------+
| 95 | 06 | 84605898 | 10.10.10 |
| 95 | 06 | 14666641 | 11.11.11 |
| 95 | 06 | 84605898 | 12.12.12 |
我的请求:
select
t.ID,
max(case when t.code = 'numVz' then t.val end) as numVz
,max(case when t.code = 'prevVz' then t.val end) as prevVz
,max(case when t.code = 'ndatVz' then t.val end) as ndatVz
from tbl_Regist t
where t.ID = 95
group by t.ID
| ID | numVz | prevVz | ndatVz |
+----|-------+----------+----------+
| 95 | 06 | 84605898 | 12.12.12 |
只返回一行,如果去掉聚合函数,它返回 9 行
解决方案
您可以使用row_number()
来添加枚举。但是,您确实需要一个排序列:
select r.ID,
max(case when r.code = 'numVz' then r.val end) as numVz,
max(case when r.code = 'prevVz' then r.val end) as prevVz,
max(case when r.code = 'ndatVz' then r.val end) as ndatVz
from (select r.*,
row_number() over (partition by id, code order by <ordering column>) as seqnum
from tbl_Regist r
) r
where r.ID = 95
group by r.ID, seqnum;
推荐阅读
- javascript - 更改类中所有元素的背景
- android - SDK39 上未处理的承诺拒绝 - SplashScreen
- css - typecipt CSS.Properties 重叠属性
- multithreading - 从不同线程和同一个线程调用 QObject 方法的首选方式
- javascript - Javascript 新语法的 Webpack 加载器
- hyperledger-fabric - Hyperledger Fabric 节点 SDK 服务器部署
- android - 在下载文件夹的应用程序特定目录中重新安装时保留文件
- selenium - 使用 pyinstaller 将 .py 转换为 .exe 后,带有代理的 Selenium 脚本不起作用
- python - AttributeError:'tuple' 对象在 postgres 上没有属性 'strftime' 问题
- r - 将特征共现与重要共现进行比较