我在尝试开发一个查询时遇到了一个小挑战。
这是我的 table 的样子:-
账户表
ClientNo AccountType Balance
1234 SUP1 25
1234 SUP1.1 35
1234 RET1 20
1111 SUP1 50
1111 DIS4 60
我正在尝试获得如下所示的结果:-
ClientNo TotSupBal TotSuppAccts TotRetBal TotRetAccts TotDisBal TotDisAccts
1234 70 2 20 1 0 0
1111 50 1 0 0 60 1
本质上,一个客户可以多次出现在 Accounts 表中,因为每个客户可以有多个账户。
帐户类型将始终以相同的字符开头,但是取决于这些帐户中有多少个,该数字可以是任何真正的数字,随后的帐户将始终是十进制然后是数字......例如第一个 SUP 帐户只是 SUP1,但是下一个 SUP 帐户将是 SUP1.1,然后是 SUP1.2 等等......
我写了以下查询
SELECT ClientNo, SUM(Balance) AS TotSupBal, COUNT(AccountType) AS TotSuppAccts
FROM Account
WHERE (AccountType LIKE 'SUP1.%') OR (AccountType = 'SUP1')
GROUP BY ClientNo
*有 2 个不同的 WHERE 子句的原因是因为我不能只使用 SUP1%,因为有像 SUP12 这样的帐户与 SUP1 不同。
此查询工作正常,但它只为 SUP 帐户类型的列表生成列表。
我如何生成相同类型的输出,但是对于每个帐户类型跨多个列?
我正在使用 Microsoft SQL 2008 R2
最佳答案
PIVOT 正是您所需要的 >> http://msdn.microsoft.com/en-us/library/ms177410(v=sql.105).aspx
这是一个完全有效的解决方案:
WITH Accounts (AccountCategory, ClientNo, Balance) as (
select
case
when AccountType like 'SUP%' then 'sup'
when AccountType like 'RET%' then 'ret'
when AccountType like 'DIS%' then 'dis'
end as AccountCategory,
ClientNo,
Balance
from Account
)
select * from (
select ClientNo, sup as TotSupBal, ret as TotRetBal, dis as TotDisBal from Accounts as SourceTable PIVOT (
SUM(Balance)
FOR AccountCategory IN ([sup], [ret], [dis])
) as pt
) as sums inner join (
select ClientNo, sup as TotSupAccts, ret as TotRetAccts, dis as TotDisAccts from Accounts as SourceTable PIVOT (
COUNT(Balance)
FOR AccountCategory IN ([sup], [ret], [dis])
) as pt
) as counts on sums.ClientNo = counts.ClientNo
在 SqlFiddle 上试试:http://sqlfiddle.com/#!6/d5e91/26
关于SQL - 困难的查询 - 将多行合并为列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14064276/