从具有复合主键的表中选择筛选记录

时间:2015-11-04 05:05:41

标签: sql sql-server sql-server-2008-r2

我在 SQL Server 2008 R2 数据库上有下表:

╔══════════════════════════╦══════════════╦══════════╗
║        Team Name         ║ Project Code ║ Actioned ║
╠══════════════════════════╬══════════════╬══════════╣
║ DC & Facilities Services ║ ZZ794419     ║ No       ║
║ DC & Facilities Services ║ ZZ794419     ║ Yes      ║
║ DC & Facilities Services ║ ZZ795164     ║ No       ║
║ DC & Facilities Services ║ ZZ795247     ║ No       ║
╚══════════════════════════╩══════════════╩══════════╝

Team NameProject Code一起是复合主键。在这种情况下,我之后返回的结果是最后3行。当(项目和团队)有多行(即上表中的前两行)时,我想只选择Actioned'Yes'的行。如果项目和团队在操作中只有'No'(即上表中的最后两行),则他们也需要包含在我的搜索结果中。

有没有办法从SELECT声明中获取结果?似乎很难定义WHERE子句以获得预期的结果。

2 个答案:

答案 0 :(得分:3)

您可以尝试对Team NameProject Code列的组合进行分组,然后使用MAX()函数选择包含'Yes'的记录对于给定的组合组合,会出现'Yes''No'

SELECT `Team Name`, `Project Code`, MAX(`Actioned`) AS 'Actioned'
FROM table
GROUP BY `Team Name`, `Project Code`

答案 1 :(得分:2)

使用SUM() OVER

;WITH CTE AS(
    SELECT *,
        Y = SUM(CASE WHEN Actioned = 'YES' THEN 1 ELSE 0 END) OVER(PARTITION BY TeamName, ProjectCode),
        N = SUM(CASE WHEN Actioned = 'NO' THEN 1 ELSE 0 END) OVER(PARTITION BY TeamName, ProjectCode)
    FROM tbl
)
SELECT 
    TeamName, ProjectCode, Actioned
FROM CTE
WHERE
    (Y = 1 AND Actioned = 'Yes')
    OR (Y = 0)

SQL Fiddle