将 2 个表连接在一起,同时使用不同的过滤器将一张表连接两次

问题描述 投票:0回答:1

我在 2 个 SQL Server 表中收集了数据:

地区

区域
a
b

转变

个人ID 日期 轮班时间 区域
12 2012-01-10 a
13 2012-01-10 a
14 2012-01-10 迟到了 a
15 2012-01-10 b

我想在这样的查询中将它们连接在一起:

区域 日期 迟到了
a 2012-01-10 12 14
a 2012-01-10 13
b 2012-01-10 15

我尝试过类似的事情:

SELECT
    AREAS.area, early.date, early.personal_id as early, 
    late, personal_id as late
FROM 
    AREAS
LEFT JOIN 
    SHIFTS AS early ON AREAS.area = early.area
LEFT JOIN 
    SHIFTS AS late ON AREAS.area = late.area
WHERE
    early.shifttime = 'early' 
    AND late.shifttime = 'late' 
    AND date = '2012-01-10'

但是输出:

区域 日期 迟到了
a 2012-01-10 12 14
a 2012-01-10 13 14
b 2012-01-10 15

是否有其他方式加入或者我是否必须在 SQL Server 中以不同的方式保存数据?

sql sql-server join
1个回答
0
投票

同一个

personal_id
area
date
下有多个
shift
,并且您想将其显示在不同行下。您可以使用
row_number()
为每个
personal_id
生成一个流水号。

row_number() over (partition by a.area, s.date, s.shifttime 
                       order by s.personal_id)

从那里您可以使用 PIVOT 查询

select area, date, early, late
from   (
           select a.area, s.date, s.shifttime, s.personal_id,
                  rn = row_number() over (partition by a.area, s.date, s.shifttime 
                                              order by s.personal_id)
           from   AREAS a
                  left join SHIFTS s on a.area = s.area
       ) d
       pivot
       (
           max (personal_id)
           for shifttime in ([early], [late])
       ) p

或者条件case表达方式

select d.area, d.date, 
       early = max(case when shifttime = 'early' then personal_id end), 
       late  = max(case when shifttime = 'late'  then personal_id end)
from   (
           select a.area, s.date, s.shifttime, s.personal_id,
                  rn = row_number() over (partition by a.area, s.date, s.shifttime 
                                              order by s.personal_id)
           from   AREAS a
                  left join SHIFTS s on a.area = s.area
       ) d
group by d.area, d.date, rn
© www.soinside.com 2019 - 2024. All rights reserved.