SQL DISTINCT用于2列WHERE第3列=值

时间:2017-07-28 06:05:54

标签: sql sql-server

我试图选择不同列的数量Col 1&第2栏第3栏="完成"。

首先,我不知道如何使分别适用于Col 1& Col 2在一起,而不是关于他们自己的列的Distinct。 其次,如何将Col 3从Distinct中排除..

SELECT COUNT(*) AS Count From 
(Select Distinct DP, RN From ECount 
Where ET = 'Complete') as rows

有什么想法吗?

例如

col1    col2    col3    
DP01    RN01    Complete    yes
DP01    RN02    Incomplete  
DP02    RN03    Complete    
DP02    RN03    Incomplete  
DP01    RN04    Complete    yes
DP02    RN05    Complete    yes
DP03    RN06    Incomplete  

结果= 3

3 个答案:

答案 0 :(得分:1)

我认为您不需要在ET部分中包含第3列(aka,col SELECT),您可以直接在WHERE语句中使用它。

所以在你的例子中:

SELECT COUNT(*) AS Count FROM 
  (SELECT DISTINCT DP, RN FROM ECount 
   WHERE ET = 'Complete'
  ) AS rows

答案 1 :(得分:0)

不要在子查询中选择ET

SELECT COUNT(*) AS Count
From  ( 
        Select Distinct DP, RN 
        From ECount 
        Where ET = 'Complete'
) as rows

答案 2 :(得分:0)

SELECT
    Count(*) AS Count
FROM
    (
        SELECT
            *
        FROM
            (
                SELECT
                    *
                FROM
                    `ECount`
                ORDER BY
                    col3 DESC
            ) AS StrongIncomplete
        GROUP BY
            col1,
            col2
    ) AS CompleteCut
WHERE
    CompleteCut.col3 = 'Complete'

有3 SELECT条陈述。

第一个重新排列表格“不完整”。优于'完成'在Col3。

第二个删除Col1,Col2中重复的行。

第三个删除Col3 =' Incomplete'

的行