[英]Use count() in CASE Expression
I have the following data and I need help creating a case expression with a condition, When more than one PPaymentID exists per PaymentID then M is Y else false.我有以下数据,我需要帮助创建一个带有条件的案例表达式,当每个 PaymentID 存在多个 PPaymentID 时,M 为 Y,否则为 false。
PaymentID ProductID PPaymentID
1456789 1398 4587934
3445738 1398 8754418
3445738 1399 8754419
I would like to see something like我想看到类似的东西
PaymentID ProductID PPaymentID M
1456789 1398 4587934 N
3445738 1398 8754418 Y
3445738 1399 8754419 Y
You can use您可以使用
SELECT *, CASE WHEN COUNT(1) OVER(PARTITION BY PaymentID) >= 2 THEN 'Y' ELSE 'N' END AS M
FROM YourTable
Since you only care whether there is another row with the same PaymentId
and a different PPaymentId
there is no need to obtain a precise count
.由于您只关心是否存在具有相同
PaymentId
和不同PPaymentId
的另一行,因此无需获取精确count
。 It is more efficient to just check if such a row exists
:只检查是否
exists
这样的行会更有效:
select PaymentId, ProductId, PPaymentId,
case when exists ( select 42 from YourTableOData as iYTOD
where iYTOD.PaymentId = YTOD.PaymentId and iYTOD.PPaymentId != YTOD.PPaymentId )
then 'Y'
else 'N' end as M
from YourTableOData as YTOD;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.