不同的代码不会工作SQL Server

时间:2015-01-23 14:37:49

标签: sql sql-server sql-server-2012 distinct

SELECT DISTINCT 
    U.Unit_ID, P.Plant_ID, P.Project_NR, U.Key_code_list,  
    S.Status_type, Kc.Key_codes4
FROM 
    Plant as P
INNER JOIN 
    Unit as U ON P.Plant_NR = U.Plant_NR
INNER JOIN 
    [dbo].[Key_code_list] as Kcl ON P.Project_NR = Kcl.Project_NR
INNER JOIN 
    Status_codes as S ON S.Status_nr = Kcl.Status
INNER JOIN 
    Key_codes as Kc ON Kc.Key_code_ID = Kcl.Key_code_list_ID

我有这个代码,它不会给我我希望的结果。我知道这可能很容易,但是我现在已经把头撞到了墙上一小时,想到为什么不问你们。

现在的结果是:

Unit_ID | Plant_ID | Project_NR | Key_code_list | Status_type | Key_code_4 | Key_code _ID
-----------------------------------------------------------------------------------------------
MEOD    | SM       | 114015     | 4             | Assigned    | AC49       | 11  | 
MLO     | SM       | 114015     | 4             | Assigned    | AC49       | 11  |
MEOD    | SM       | 114015     | 4             | Assigned    | AC47       | 12  | 
MLO     | SM       | 114015     | 4             | Assigned    | AC47       | 12  |

结果现在两次,但结果不正确。我很想得到答案一次。有人可以帮帮我吗?

期望的结果是:

  MEOD    | SM       | 114015     | 4             | Assigned    | AC49       | 12  | 
  MLO     | SM       | 114015     | 4             | Assigned    | AC47       | 11  |



SELECT * FROM dbo.Key_Code_List WHERE Project_NR = '114015'

Key_code_list | Status | Plant_ID | Textfield_unit | Unit_ID | Key_code_list_ID | Project_NR
4             | 2      | SM       | NULL           | MLO     | 11               | 114015
4             | 2      | SM       | NULL           | MEOD    | 12               | 114015

1 个答案:

答案 0 :(得分:0)

您在Key_Code_List表的连接中缺少Unit_ID字段。

SELECT DISTINCT 
    U.Unit_ID, P.Plant_ID, P.Project_NR, U.Key_code_list,  
    S.Status_type, Kc.Key_codes4
FROM 
    Plant as P
INNER JOIN 
    Unit as U ON P.Plant_NR = U.Plant_NR
INNER JOIN 
    [dbo].[Key_code_list] as Kcl ON 
        P.Project_NR = Kcl.Project_NR AND 
        U.Unit_ID = Kcl.Unit_ID -- add this to the JOIN condition
INNER JOIN 
    Status_codes as S ON S.Status_nr = Kcl.Status
INNER JOIN 
    Key_codes as Kc ON Kc.Key_code_ID = Kcl.Key_code_list_ID