从两个表中选择Distinct Records

时间:2014-11-04 10:32:07

标签: sql-server

两个表(MasterTable,列ID,名称)DetailTable with Columns(MasterID,Status) 现在记录显示如果我加入两个表并放置像

这样的查询
SELECT dbo.testMaster.Name,testDetail.Status
FROM   dbo.testDetail 
INNER JOIN dbo.testMaster ON dbo.testDetail.testID = dbo.testMaster.ID

它显示以下结果

khalid      Pass
Khalid      WithDraw
Khalid      Fail
Hamid       Fail
Hamid       WithDraw
Mike        WithDraw

我想选择khalid,如果他有“通过”值,它应该跳过WithDraw并为他失败。 对于Hamid,我们有两个记录,但优先级应该是撤销,所以它应该跳过了hamid的失败。迈克只有一个记录,所以它应该选择他的记录。

结果应该像

Khalid Pass
Hamid WithDraw 
Mike WithDraw

3 个答案:

答案 0 :(得分:1)

另一种方式:

SELECT
    *
FROM (SELECT
    dbo.testMaster.Name
    ,testDetail.Status
    ,ROWN = ROW_NUMBER() OVER (PARTITION BY dbo.testMaster.Name ORDER BY 
    CASE
        WHEN testDetail.Status = 'Pass' THEN 3
        WHEN testDetail.Status = 'WithDraw' THEN 2
        WHEN testDetail.Status = 'Fail' THEN 1
        ELSE 0
    END DESC
    )

FROM dbo.testDetail
JOIN dbo.testMaster
    ON dbo.testDetail.testID = dbo.testMaster.ID) a
WHERE ROWN = 1

答案 1 :(得分:0)

SELECT dbo.testMaster.Name, 
       case min(case testDetail.Status 
                     when 'Pass' then 1 
                     when 'WithDraw' then 2 
                     when 'Fail' then 3
                end)
            when 1 then 'Pass'
            when 2 then 'WithDraw'
            when 3 then 'Fail'
       end
FROM   dbo.testDetail 
INNER JOIN dbo.testMaster ON dbo.testDetail.testID = dbo.testMaster.ID
GROUP BY dbo.testMaster.Name;

您可以使用CASE WHEN将状态的字符串表示形式转换为数字,并获取每个Name的最小状态。然后转换回来。

答案 2 :(得分:0)

使用 Case statement 分配优先级,并为所有用户选择最小值。试试这个。

CREATE TABLE #result
  (
     NAME VARCHAR(50),
     stat VARCHAR(50)
  )

INSERT INTO #result
VALUES      ('khalid','Pass'),
            ('Khalid','WithDraw'),
            ('Khalid','Fail'),
            ('Hamid','Fail'),
            ('Hamid','WithDraw'),
            ('Mike','WithDraw')

WITH cte
     AS (SELECT CASE stat
                  WHEN 'pass' THEN 1
                  WHEN 'WithDraw' THEN 2
                  ELSE 3
                END priority,
                *
         FROM   #result)
SELECT a.NAME,
       a.stat
FROM   cte a
       JOIN(SELECT Min(priority) priority,
                   NAME
            FROM   cte
            GROUP  BY NAME) b
         ON a.priority = b.priority
            AND a.NAME = b.NAME 

<强>输出

name    stat
-----   --------
Hamid   WithDraw
khalid  Pass
Mike    WithDraw