如何使用SQL将条件应用于多行?何时 /分区
我正在尝试创建一个根据一组条件显示“是”或“否”的列。如果满足条件,则“是”将应用于组中的每一行(即使组中仅某些行满足条件)。
这是我到目前为止所拥有的,但它产生了一个错误。本质上,如果属于同一货件 ID 的任何行的货件名称 = 'CAL',我希望结果为“是”。
CASE WHEN shipment.name = 'CAL' THEN 'Yes' ELSE 'No' OVER (PARTITION BY shipment.id) END AS fulfil
表
shipment.idshipment.name | 您可以在下面看到我的理想 | 履行 |
---|---|---|
1 | CAL | 是 |
1 | NEV | 是 |
2 | PEN | 否 |
2 | NEV | 否 |
I am trying to create a column that shows Yes or No based on a set of conditions. If the conditions are met, then 'Yes' would apply to every row in the group (even if the conditions are only met by some of the rows in the group).
This is what I have so far but it's yielding an error. In essence, if any of the rows belonging to the same shipment id has shipment name = 'CAL', I want the result to be 'Yes'.
CASE WHEN shipment.name = 'CAL' THEN 'Yes' ELSE 'No' OVER (PARTITION BY shipment.id) END AS fulfil
You can see my ideal table below
shipment.id | shipment.name | fulfil |
---|---|---|
1 | CAL | Yes |
1 | NEV | Yes |
2 | PEN | No |
2 | NEV | No |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
当名称带有“CAL”时,您可以使用
MAX()
窗口函数返回'Yes'
。如果不存在,
MAX()
将返回NULL
,并通过COALESCE()'No'
代码>:You can use
MAX()
window function to return'Yes'
when there is a name with 'CAL'.If there isn't,
MAX()
will returnNULL
which will be turned to'No'
byCOALESCE()
: