将表中的某些列设置为0

时间:2019-06-28 16:23:46

标签: sql sql-server

我的问题是我想为每个缺少的LAST_YARD_ROW设置0 假设每个公园都有自己的编号或行数。

问题出在交叉联接线上。

SELECT  
    lypb.last_yard_park,
    lypb.last_yard_bay,
    lyr.last_yard_row,
    0 top_tier
FROM 
    (SELECT DISTINCT
         last_yard_bay,LAST_YARD_PARK 
     FROM
         TOWERS) lypb
CROSS JOIN 
    (SELECT DISTINCT LAST_YARD_ROW FROM TOWERS) lyr (last_yard_row)
WHERE 
    NOT EXISTS (SELECT *
                FROM TOWERS t
                WHERE t.last_yard_bay = lypb.last_yard_bay
                  AND t.LAST_YARD_PARK= lypb.LAST_YARD_PARK
                  AND t.last_yard_row = lyr.last_yard_row)

UNION

SELECT * 
FROM TOWERS
ORDER BY 
    LAST_YARD_PARK, LAST_YARD_BAY, LAST_YARD_ROW;

这是我的输出:

 park   Bay    Row      Tier
 A1     007    00A      01
 A1     007    00B      0
 A1     007    00C      0
 A1     007    00D      0
 A1     007    00E      05
 A2     007    00A      0
 A2     007    00B      02
 A2     007    00C      0
 A2     007    00D      0
 A2     007    00E      0

预期输出是因为公园A2仅具有00A 00B 00C

 park   Bay    Row      Tier
 A1     007    00A      01
 A1     007    00B      0
 A1     007    00C      0
 A1     007    00D      0
 A1     007    00E      05
 A2     007    00A      0
 A2     007    00B      02
 A2     007    00C      0

1 个答案:

答案 0 :(得分:0)

lyr.LAST_YARD_ROW上进行交叉联接之​​后,我只需要添加一个过滤器即可使其工作:

SELECT  
    lypb.last_yard_park,
    lypb.last_yard_bay,
    lyr.last_yard_row,
    0 top_tier
FROM 
    (SELECT DISTINCT
    last_yard_bay,LAST_YARD_PARK 
FROM
     TOWERS) lypb
CROSS JOIN 
     (SELECT DISTINCT LAST_YARD_ROW FROM TOWERS) lyr (last_yard_row)
WHERE 
    lyr.LAST_YARD_ROW IN 
    (select distinct LAST_YARD_ROW FROM TOWERS 
    WHERE LAST_YARD_PARK=lypb.LAST_YARD_PARK )
AND
    NOT EXISTS (SELECT *
            FROM TOWERS t
            WHERE t.last_yard_bay = lypb.last_yard_bay
              AND t.LAST_YARD_PARK= lypb.LAST_YARD_PARK
              AND t.last_yard_row = lyr.last_yard_row)

UNION

SELECT * 
FROM TOWERS
ORDER BY 
    LAST_YARD_PARK, LAST_YARD_BAY, LAST_YARD_ROW;