查询返回重复,尽管嵌套查询返回没有重复

时间:2016-11-03 12:17:23

标签: sql sql-server

我在下面有以下查询可行。然而,它是返回重复,我不明白。

前三个嵌套查询没有重复,所以我不明白为什么最终结果重复了sedols?

 ;with b as
 (
    select sedol, wgt from myTbl
    where name = 'B'
 ), j as 
 (
    select sedol, wgt from myTbl
    where name = 'J'
 ), s as
 (
    select sedol, wgt from myTbl
    where name = 'S'
 ), hlds as
 (
    select coalesce(b.sedol, j.sedol, s.sedol) sedol, isnull(b.wgt,0) bw, isnull(j.wgt,0) jw, isnull(s.wgt,0) sw
    from b full outer join j on b.sedol = j.sedol
    full outer join s on b.sedol = s.sedol  
 )
 select hlds.* from hlds
 order by sedol

示例数据

myTbl 

sedol    name   wgt
abc      b      1
abc      j      2
abc      s      3
def      j      2
def      s      4

当前结果

abc    1      2      3
def    0      2      0
def    0      0      4

应该是

abc    1      2      3
def    0      2      4

1 个答案:

答案 0 :(得分:3)

让我们改进这个查询并使用条件聚合保存连接:

SELECT t.sedol,
       MAX(CASE WHEN t.name = 'B' THEN t.wgt END) as [b],
       MAX(CASE WHEN t.name = 'J' THEN t.wgt END) as [j],
       MAX(CASE WHEN t.name = 'S' THEN t.wgt END) as [s]
FROM YourTable t
GROUP BY t.sedol