连接表两次时重复列

时间:2016-10-04 06:41:30

标签: sql-server

当我加入一个表两次从表2中获取不同的数据时,如果表2获得不同的行计数数据,则某些列会重复。

select 
o.order_no
,sr.reason as reason1
,datediff(minute,s.begin_stop,s.end_stop) as s1
,sr2.reason as reason2
,datediff(MINUTE,s2.begin_stop,s2.end_stop) as s2
from [order] o 
left join [stops] s on s.order_id=o.id and s.section='print'
join [stopreason] sr on s.error_code=sr.code
left join [stops] s2 on s2.order_id=o.id and s2.section='laminate1'
join [stopreason] sr2 on sr2.code=s2.error_code
where datepart(ww,o.date_onexit)=39
order by order_no

我得到了这个结果

enter image description here

1 个答案:

答案 0 :(得分:1)

试试这个:

;WITH part1 AS (
    select  o.order_no,
            sr.reason as reason1,
            datediff(minute,s.begin_stop,s.end_stop) as s1,
            ROW_NUMBER() OVER (PARTITION BY o.order_no ORDER BY o.order_no) rn
    from [order] o 
    left join [stops] s 
        on s.order_id=o.id and s.section='print'
    join [stopreason] sr 
        on s.error_code=sr.code
    where datepart(ww,o.date_onexit)=39
), part2 AS (
    select  o.order_no,
            sr2.reason as reason2,
            datediff(MINUTE,s2.begin_stop,s2.end_stop) as s2,
            ROW_NUMBER() OVER (PARTITION BY o.order_no ORDER BY o.order_no) as rn
    from [order] o 
    left join [stops] s2 
        on s2.order_id=o.id and s2.section='laminate1'
    join [stopreason] sr2 
        on sr2.code=s2.error_code
    where datepart(ww,o.date_onexit)=39
)

SELECT  p1.order_no,
        p1.reason1,
        p1.s1,
        p2.reason2,
        p2.s2
FROM part1 p1
LEFT JOIN part2 p2 
    ON p1.order_no = p2.order_no AND p1.rn = p2.RN
order by p1.order_no

第一次CTE(part1)收集section='print'的数据,第二次收集section='laminate1'的数据。我们添加ROW_NUMBER()。然后加入两个CTE。

还有一种方法:

;WITH part1 AS (
    select  o.order_no,
            sr.reason as reason,
            datediff(minute,s.begin_stop,s.end_stop) as s,
            s.section,
            ROW_NUMBER() OVER (PARTITION BY o.order_no,s.section ORDER BY o.order_no) rn
    from [order] o 
    left join [stops] s 
        on s.order_id=o.id and (s.section='print' or s.section='laminate1' )
    join [stopreason] sr 
        on s.error_code=sr.code
    where datepart(ww,o.date_onexit)=39
)

SELECT  p1.order_no,
        p1.reason1,
        p1.s1,
        p2.reason2,
        p2.s2
FROM part1 p1
LEFT JOIN part1 p2
    ON p1.order_no = p2.order_no AND p1.rn = p2.RN AND p2.section='laminate1'
WHERE p1.section='print'
order by p1.order_no