加入返回单行

时间:2014-12-27 08:13:11

标签: sql select join case

我需要编写一个SQL查询来填充DELTA列。如果状态已更改,则为YES,否则为NO。我尝试过INNER JOINS,但它不起作用。

[Current Week Project]      |       [Last Week Project] 
ProjectID   Status  Delta   |   ProjectID   Status
       8614 Amber           |   8614    Green
       8548 Unknown         |   8548    Unknown
       2591 Green           |   2591    Green
       7813 Red             |   7813    Green
       8413 Green           |   8413    Green
       8183 Green           |   8183    Green
       7431 Red             |   7431    Red
       7399 Green           |   7399    Green
       7776 Green           |   7776    Green
       8609 Green           |   8609    Green
       8068 Red             |   8068    Amber
       8019 Green           |   8019    Green
       7799 Green           |   7799    Green
       6727 Amber           |   6727    Unknown
       7482 Green           |   7482    Green
       8384 Red             |   8384    Green

SELECT a.[Status],b.[Status] 
FROM [Current Week Project] a 
INNER JOIN [Last Week Project] b  
ON a.[ProjectID]= b.[ProjectID]

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT a.[ProjectID], a.[Status], b.[Status], 
      (CASE WHEN a.[Status] = b.[Status] THEN 'No' ELSE 'YES' END) AS Delta
FROM [Current Week Project] a 
INNER JOIN [Last Week Project] b ON a.[ProjectID]= b.[ProjectID];