案例陈述结合三个表

时间:2019-12-06 22:40:56

标签: sql sql-server-2008 case

SELECT 
    RS00200M.ACTION_NO,RS00200M.ACTION_CD,
    CAST(RS00200M.RESOLUTION_DT AS DATE) AS RESOLVED_DATE,
    CASE 
       WHEN (RS00200M.RESOLUTION_CD = 'CMPLT') 
          THEN (1) ELSE (0) 
    END AS COUNT_COMPLETE_SO,
    CASE 
       WHEN (RS00200M.ACTION_CD IN ('MTFRD', 'MTSRD')) 
          THEN (1) ELSE (0) 
    END AS COUNT_FINAL_INITIAL_SO,
    CASE 
       WHEN (RS00200M.ACTION_CD = 'RERTW') 
          THEN (1) ELSE (0) 
    END AS COUNT_ERT_CHANGE_SO,
    CASE 
       WHEN (RS00200M.ACTION_CD = 'MTEXE' AND UM00300M.SHORT IN ('058', '034', '100'))
          THEN (1) ELSE (0) 
    END AS COUNT_SHORT,
    CASE 
       WHEN (RS00200M.ACTION_CD = 'MTRRD') 
          THEN (1) ELSE (0) 
    END AS COUNT_REREAD_SO,
    CASE 
       WHEN (RS00200M.ACTION_CD = 'HIUSE') 
          THEN (1) ELSE (0) 
    END AS COUNT_HIUSE,
    CASE 
       WHEN (RS00200M.ACTION_CD = 'LKADJ') 
          THEN (1) ELSE (0) 
    END AS COUNT_LKADJ_SO
FROM
    RS00200M, UM00300M, RS00210M
LEFT JOIN 
    RS00210M ON RS00200M.ACTION_CD = RS00210M.ACTION_CD
LEFT JOIN 
    UM00300M ON UM00300M.SERIAL_NO = UM00210M.SERIAL_NO

我遇到错误

  

第208条消息,第16级,状态1,第1行
  无效的对象名称“ RS00210M”

有什么建议吗?预先感谢-数据库中确实存在这三个表

1 个答案:

答案 0 :(得分:2)

首先,您需要修复from子句。每个表应该只出现一次

FROM RS00200M
LEFT JOIN RS00210M on RS00200M.ACTION_CD=RS00210M.ACTION_CD
LEFT JOIN UM00300M on UM00300M.SERIAL_NO=UM00210M.SERIAL_NO

此外,您应该在CASE表达式中删除此多余的括号。通常,这是

CASE WHEN (RS00200M.RESOLUTION_CD = 'CMPLT') THEN (1) ELSE (0) END AS COUNT_COMPLETE_SO

应拼写:

CASE WHEN RS00200M.RESOLUTION_CD = 'CMPLT' THEN 1 ELSE 0 END AS COUNT_COMPLETE_SO

这应该足以使您的查询正常运行。

附带说明:查询的结构倾向于表明您可能需要条件聚合。如果是这样,则其结构如下:

SELECT 
    RS00200M.ACTION_NO,
    RS00200M.ACTION_CD,
    CAST(RS00200M.RESOLUTION_DT AS DATE) AS RESOLVED_DATE,
    SUM(CASE WHEN RS00200M.RESOLUTION_CD = 'CMPLT' THEN 1 ELSE 0 END) AS COUNT_COMPLETE_SO,
    --- ... more SUM(CASE ...) expressions here ...
FROM RS00200M
LEFT JOIN RS00210M on RS00200M.ACTION_CD=RS00210M.ACTION_CD
LEFT JOIN UM00300M on UM00300M.SERIAL_NO=UM00210M.SERIAL_NO
GROUP BY
    RS00200M.ACTION_NO,
    RS00200M.ACTION_CD,
    CAST(RS00200M.RESOLUTION_DT AS DATE) AS RESOLVED_DATE