如何根据此记录的值获取一对多关系中的单个记录

时间:2016-02-26 15:11:48

标签: sql sql-server

我有两个表,一个包含项目列表,另一个包含此项目的请求。我想获得项目编号和请求记录。状态可以是:红色,黄色,绿色,打开

如何确保显示的1状态记录遵循以下逻辑:当存在红色时,显示红色,当没有红色但有黄色时显示此黄色等。 ..

;WITH 
numberTest as(
    SELECT dbo.ServiceRequest.ID as numId,
    ROW_NUMBER() OVER (PARTITION BY dbo.ServiceRequest.Project_ID order by     Project_ID) AS RN1
    FROM dbo.ServiceRequest         
),

CTEVrequest AS
(
    SELECT dbo.ServiceRequest.ID,   dbo.ServiceRequest.Project_ID   
    FROM         dbo.ServiceRequest     
    LEFT JOIN    numberTest ON numberTest.numId = dbo.ServiceRequest.ID 
    WHERE numberTest.RN1 = 1
    AND 
    dbo.ServiceRequest.ID = CASE 

    WHEN EXISTS( 
    select srvReq.ID
    from  dbo.ServiceRequest as srvReq  
    where requestStatus.ServiceStatus = 'R' AND srvReq.Project_ID =     dbo.ServiceRequest.Project_ID)
    THEN (select srvReq.ID
    from  dbo.ServiceRequest as srvReq  
    where requestStatus.ServiceStatus = 'R' AND srvReq.Project_ID =     dbo.ServiceRequest.Project_ID) 

    WHEN EXISTS( 
    select srvReq.ID
    from  dbo.ServiceRequest as srvReq  
    where requestStatus.ServiceStatus = 'Y' AND srvReq.Project_ID =     dbo.ServiceRequest.Project_ID)
    THEN (select srvReq.ID
    from  dbo.ServiceRequest as srvReq  
    where requestStatus.ServiceStatus = 'Y' AND srvReq.Project_ID =     dbo.ServiceRequest.Project_ID) 
END) 

SELECT  DISTINCT
    dbo.Project.ProjectNumber, 
    dbo.Project.ID, 
    CTEVrequest.ServiceReqStatus,
    CTEVrequest.ServiceStatus                    
    FROM         dbo.Project
    LEFT JOIN    CTEVrequest ON CTEVrequest.Project_ID = dbo.Project.ID
    LEFT JOIN     dbo.Project ON dbo.ServiceRequest.Project_ID = dbo.Project.ID 

问题是我得到“子查询返回超过1的值”错误,我不知道如何检查结果是否存在红色记录,如果没有选择带黄色的记录等等。

2 个答案:

答案 0 :(得分:1)

可能我没理解你,但看起来你的查询应该这样做:

SELECT *
FROM dbo.Project p
OUTER APPLY
(
    SELECT TOP 1 sr.*
    FROM dbo.ServiceRequest sr
    WHERE sr.Project_ID = p.Project_ID
      /* AND sr.ServiceStatus in ('R', 'Y') */
    ORDER BY
      CASE
        WHEN sr.ServiceStatus = 'R' THEN 1
        WHEN sr.ServiceStatus = 'Y' THEN 2
        ELSE 3
      END
) sr

答案 1 :(得分:0)

为什么不创建一个充当状态键的表?例如:

IF OBJECT_ID('tempdb..#LevelKey') IS NOT NULL
    DROP TABLE #LevelKey;

CREATE TABLE #LevelKey 
    (LevelText [varchar](255),
    LevelValue INT);

INSERT INTO #LevelKey VALUES 
    ('Red',1),
    ('Orange',2),
    ('Yellow',3),
    ('Green',4);

现在,将项目级别加入此键。当你想获得最高级别时,你可以做类似的事情:

SELECT TOP 1 *
FROM Table
INNER JOIN #LevelKey ON LevelText = Whatever
ORDER BY LevelValue ASC

但这只适用于一个人。所以我甚至不确定为什么要包含它。要带回一个小组,你将不得不做这样的事情:

SELECT ProjectID, MAX(LevelValue) AS LevelValue
FROM Table
INNER JOIN #LevelKey ON LevelText = Whatever
GROUP BY ProjectID