sql - 在 SQL 中多次旋转同一列
问题描述
我已经搜索了该站点,即使关于这个问题有多个问题,我也不能完全理解它们,因为我是 SQL 的新手,或者它们不完全适合我的问题。
所以我有一张这样的桌子:
ID Label AmountA AmountB CurrA CurrB
1 7 400 4 usd usd
2 7 500 10 eur eur
3 7 1000 500 usd usd
1 8 800 1 usd usd
2 8 9000 0 eur eur
3 9 100 0 usd usd
但我需要这样:
ID AmountA1 CurrAmountA1 AmountA2 CurrAmountA2 AmountA3 CurrAmountA3 AmountB1 CurrAmountB1 AmountB2 CurrAmountB2 AmountB3 CurrAmountB3
1 400 USD 800 USD NULL NULL 4 USD 1 USD NULL NULL
2 500 EUR 9000 EUR NULL NULL 10 EUR 0 EUR NULL NULL
3 1000 USD NULL NULL 100 USD 500 USD NULL NULL 0 USD
我已经设法执行以下代码:
SELECT ID,
isnull([7],0) as AmountA1,
isnull([8],0) as AmountA2,
isnull([9],0) as AmountA3,
FROM
(SELECT ID, Label, AmountA, AmountB,CurrA, CurrB FROM mytable ) ps
PIVOT
( sum([AmountA]) FOR Label IN
( [7],
[8],
[9])) as pvt
我只是让 AmountA 旋转,但我不知道如何包含其他的。
我不知道是否值得说我需要在数百万行上执行此操作,并且 Label 可以有 10 个不同的值,并且我需要它尽可能快。
谢谢
解决方案
我只会使用条件聚合:
select id,
max(case when seqnum = 1 then amountA end) as amountA_1,
max(case when seqnum = 1 then currA end) as currA_1,
max(case when seqnum = 2 then amountA end) as amountA_2,
max(case when seqnum = 2 then currA end) as currA_2,
max(case when seqnum = 3 then amountA end) as amountA_3,
max(case when seqnum = 3 then currA end) as currA_3,
max(case when seqnum = 1 then amountB end) as amountB_1,
max(case when seqnum = 1 then currB end) as currB_1,
max(case when seqnum = 2 then amountB end) as amountB_2,
max(case when seqnum = 2 then currB end) as currB_2,
max(case when seqnum = 3 then amountB end) as amountB_3,
max(case when seqnum = 3 then currB end) as currB_3
from (select t.*,
row_number() over (partition by id order by label) as seqnum
from t
) t
group by id;
推荐阅读
- javascript - Puppeteer 浏览器和页面即时关闭,page.evaluate 不适用于 bloc 2
- database - 限制 MariaDB 中小数点后的位置数
- laravel - 在我报告错误后修复 - laravel 新项目 --auth 不会创建 HomeController.php
- azure - 使用 U-SQL 读取列数未知的 Excel 文件时如何避免最后一列值重复
- c# - 如何使用包含“ODM”之类的值的 C# 在 excel 中过滤整个列?
- java-stream - 为什么 Hybris modelService.save() 在 ifPresent() 方法中不起作用?
- windows-7 - CDATA [Microsoft.PointOfService.PosControlException:消息访问端口'COM10'被拒绝。/(另一个错误''通信(端口)故障''
- javascript - Node Js无法读取未定义的属性
- verilog - 为什么仿真卡在 Vivado 中
- azure-devops - azure devops - 我的工作排了很长时间