Che*_*lin 2 sql t-sql sql-server sql-server-2008
我的目标是将所有3行连接到一行.我试图只回到1行.
Run Code Online (Sandbox Code Playgroud)select br_data.acct_id , bs_accts.acct_num, case br_data.recmethod when 1 then count(br_data.recmethod) else 0 end as "Open", case br_data.recmethod when 2 then count(br_data.recmethod) else 0 end as "Closed", case br_data.recmethod when 0 then count(br_data.recmethod) else 0 as "Suspended" from br_data , bs_accts where br_data.acct_id = bs_accts.acct_id and br_data.acct_id = '427' group by br_data.acct_id , bs_accts.acct_num , br_data.recmethod order by br_data.acct_id
目前的结果:
Run Code Online (Sandbox Code Playgroud)acct_id acct_num open closed suspended 427 0060-1537100-OLD 0 0 376818 427 0060-1537100-OLD 2279474 0 0 427 0060-1537100-OLD 0 82675 0
期望的结果:
Run Code Online (Sandbox Code Playgroud)acct_id acct_num open closed suspended 427 0060-1537100-OLD 2279474 82675 376818
只需br_data.recmethod
从您的GROUP BY
条款中删除:
SELECT
bd.acct_id,
ba.acct_num,
SUM(CASE WHEN bd.recmethod = 1 THEN 1 ELSE 0 END) AS [Open],
SUM(CASE WHEN bd.recmethod = 2 THEN 1 ELSE 0 END) AS [Closed],
SUM(CASE WHEN bd.recmethod = 0 THEN 1 ELSE 0 END) AS [Suspended]
FROM br_data bd
INNER JOIN bs_accts ba
ON ba.acct_id = bs.acct_id
WHERE
bd.acct_id = '427' -- You may want to remove the quotes if this column is of INT type
GROUP BY
bd.acct_id, bs.acct_num
ORDER BY bd.acct_id
Run Code Online (Sandbox Code Playgroud)
笔记
JOIN
语法.427
如果ba.account_id
是INT
数据类型,您可能希望删除引号.[]
括起列名称.