我在 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 Name
和Project Code
一起是复合主键。在这种情况下,我之后返回的结果是最后3行。当(项目和团队)有多行(即上表中的前两行)时,我想只选择Actioned
为'Yes'
的行。如果项目和团队在操作中只有'No'
(即上表中的最后两行),则他们也需要包含在我的搜索结果中。
有没有办法从SELECT
声明中获取结果?似乎很难定义WHERE
子句以获得预期的结果。
答案 0 :(得分:3)
您可以尝试对Team Name
和Project 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)