如何在SQL结果中识别唯一的行值?

时间:2018-03-07 00:04:06

标签: sql sql-server tsql

我有两个表,EmployeeEmployeeBenefit

Employee表格有Id字段

EmployeeBenefit表包含EmployeeIdCashValuePercentage字段。

规则是:

CashValue表的

PercentageEmployeeBenefit字段是     相互排斥;对于EmployeeBenefit表中的任何行,一次     CashValue字段具有值,Percentage字段应为null,反之亦然。   但是,允许一行包含null CashValue字段和null Percentage字段。

一名员工可以有多个EmployeeBenefit行(或者没有行     所有),他/她可以有不超过一个Percentage字段     EmployeeBenefit表有价值。

以下是EmployeeBenefit表的示例:

+------------+-----------+------------+
| EmployeeId | CashValue | Percentage |
+------------+-----------+------------+
| A          | NULL      | 80         |
| A          | 20        | NULL       |
| A          | 15        | NULL       |
| A          | NULL      | NULL       |
| B          | NULL      | 60         |
| C          | 15        | NULL       |
| C          | 10        | NULL       |
+------------+-----------+------------+

我想知道员工唯一的好处是Percentage。 什么是正确的SQL脚本?

我想让它看起来像:

 SELECT ......
 FROM Employee WITH(NOLOCK)
 OUTER APPLY
 (
   SELECT .......... AS HasOnlyPercentBenefit
   FROM EmployeeBenefit
   WHERE Employee.Id = EmployeeBenefit.EmployeeId
 )

谢谢。

2 个答案:

答案 0 :(得分:0)

[DEMO]

我会使用条件聚合来获取EmployeeId,null只有CashValuePercentage只有

的值
SELECT *, 'Yes' AS HasOnlyPercentBenefit
FROM Employee e
INNER JOIN EmployeeBenefit eb ON e.Id = eb.EmployeeId
WHERE e.Id IN(
    SELECT e.Id 
    FROM Employee e
    INNER JOIN EmployeeBenefit eb ON e.Id = eb.EmployeeId
    GROUP BY e.Id
    HAVING SUM(CASE WHEN eb.CashValue IS NULL THEN 1 ELSE 0 END) = 1
        AND SUM(CASE WHEN eb.Percentage IS NOT NULL THEN 1 ELSE 0 END) = 1)

enter image description here

答案 1 :(得分:0)

GROUP BY使用HAVING子句过滤掉只有百分比权益的员工。

SELECT e.id  
FROM Employee e
INNER JOIN EmployeeBenefit b on b.EmployeeId = e.id
GROUP BY e.id
HAVING COUNT(*) = 1 AND
       MAX(b.Percentage) IS NOT NULL