与 MS SQL Server 完全联接
Posted
技术标签:
【中文标题】与 MS SQL Server 完全联接【英文标题】:Full join with MS SQL Server 【发布时间】:2022-01-12 04:57:24 【问题描述】:我想用全连接来解决这个 leetcode 问题:https://leetcode.com/problems/reformat-department-table/
问题是,由于并非所有月份都在所有部门 ID 中,所以我得到了一个空行,应该针对部门 3。这种类型的问题是否有可能通过完全连接来解决?
/* 在下面写下你的 T-SQL 查询语句 */
select m1.id,
m1.revenue as Jan_Revenue,
m2.revenue as Feb_Revenue,
m3.revenue as Mar_Revenue,
m4.revenue as Apr_Revenue,
m5.revenue as May_Revenue,
m6.revenue as Jun_Revenue,
m7.revenue as Jul_Revenue,
m8.revenue as Aug_Revenue,
m9.revenue as Sep_Revenue,
m10.revenue as Oct_Revenue,
m11.revenue as Nov_Revenue,
m12.revenue as Dec_Revenue
from (select * from Department where month = 'Jan') m1
full join (select * from Department where month = 'Feb') m2
on m1.id = m2.id
full join (select * from Department where month = 'Mar') m3
on m2.id = m3.id
full join (select * from Department where month = 'Apr') m4
on m3.id = m4.id
full join (select * from Department where month = 'May') m5
on m4.id = m5.id
full join (select * from Department where month = 'Jun') m6
on m5.id = m6.id
full join (select * from Department where month = 'Jul') m7
on m6.id = m7.id
full join (select * from Department where month = 'Aug') m8
on m7.id = m8.id
full join (select * from Department where month = 'Sep') m9
on m8.id = m9.id
full join (select * from Department where month = 'Oct') m10
on m9.id = m10.id
full join (select * from Department where month = 'Nov') m11
on m10.id = m11.id
full join (select * from Department where month = 'Dec') m12
on m11.id = m12.id
【问题讨论】:
我认为他们只是在那里寻找一个固定的支点。 这里使用FULL JOIN
并不是一个很好的选择,但是如果你想使用它,你可能需要更改第一个字段m1.id
。如果 m1 没有该月的行,则 ID 将为 NULL。相反,它需要是任何 ID,例如 COALESCE(m1.id, m2.id, m3.id, m4.id, m5.id, m6.id, m7.id, m8.id, m9.id, m10.id, m11.id, m12.id)
- 注意 COALESCE 在列表中找到第一个非 NULL 记录。
【参考方案1】:
而不是对 Department 表执行 12 遍,只需对 12 个 case 语句执行 1 遍:
Select id, sum(Case When month='Jan' Then revenue Else 0 End) as JanRevenue
, sum(Case When month='Feb' Then revenue Else 0 End) as FebRevenue
, sum(Case When month='Mar' Then revenue Else 0 End) as MarRevenue
, sum(Case When month='Apr' Then revenue Else 0 End) as AprRevenue
, sum(Case When month='May' Then revenue Else 0 End) as MayRevenue
, sum(Case When month='Jun' Then revenue Else 0 End) as JunRevenue
, sum(Case When month='Jul' Then revenue Else 0 End) as JulRevenue
, sum(Case When month='Aug' Then revenue Else 0 End) as AugRevenue
, sum(Case When month='Sep' Then revenue Else 0 End) as SepRevenue
, sum(Case When month='Oct' Then revenue Else 0 End) as OctRevenue
, sum(Case When month='Nov' Then revenue Else 0 End) as NovRevenue
, sum(Case When month='Dec' Then revenue Else 0 End) as DecRevenue
From Department
Group by id
【讨论】:
以上是关于与 MS SQL Server 完全联接的主要内容,如果未能解决你的问题,请参考以下文章