我有两个表,Employee
和EmployeeBenefit
。
Employee
表格有Id
字段
EmployeeBenefit
表包含EmployeeId
,CashValue
和Percentage
字段。
规则是:
CashValue
表的 Percentage
和EmployeeBenefit
字段是
相互排斥;对于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
)
谢谢。
答案 0 :(得分:0)
我会使用条件聚合来获取EmployeeId,null
只有CashValue
而Percentage
只有
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)
答案 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