具有分组依据的动态列值(sql server 和 Linq)
我有一个表格Plan
,其中包含以下示例数据
我想按 PlanMonth 汇总结果,对于 PlanStatus,我希望如果其任何(在组中)值是 Drafted
,我会在结果中起草,否则 Under Approval
。我已经使用以下查询完成了此操作,
select PlanMonth, case when Flag=1 then 'Drafted' else 'Under Approval' end as PlanStatus
from
(select p.PlanMonth, Max(CASE WHEN p.PlanStatus = 'Drafted' THEN 1 ELSE 0 END) Flag
from Plans p
group by p.PlanMonth
) inquery
i have a table Plan
with following sample data
i want to aggregate the result by PlanMonth and for PlanStatus i want that if any of its (in a group) values is Drafted
i get drafted in the result and Under Approval
otherwise. i have done it using following query
select PlanMonth, case when Flag=1 then 'Drafted' else 'Under Approval' end as PlanStatus
from
(select p.PlanMonth, Max(CASE WHEN p.PlanStatus = 'Drafted' THEN 1 ELSE 0 END) Flag
from Plans p
group by p.PlanMonth
) inquery
i have consulted this blog post. Is there something wrong with it? Moreover, if someone can help me translate it to linq i will be grateful
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的查询将会起作用。
根据您提供的示例数据,可以稍微简化一下。
如果
PlanStatus
中的值按字母顺序排序在Drafted
之前,则此方法将不起作用。The query you have will work.
With the sample data you have provided it can be simplified a bit.
This will not work if you have values in
PlanStatus
that is alphabetically sorted beforeDrafted
.以下 Linq 查询对我有用
Following Linq query worked for me