多个字段的 CASE 语句结果
运行 PostgreSQL 7.x(是的,我正在升级)
示例:
SELECT
CASE
WHEN "substring"(t."Field"::text, 0, 3) = '01'::text THEN 'group one'::text
WHEN "substring"(t."Field"::text, 0, 4) = '123'::text THEN 'group one'::text
WHEN "substring"(t."Field"::text, 0, 5) = '4567'::text THEN 'group two'::text
WHEN "substring"(t."Field"::text, 0, 6) = '99999'::text THEN 'group three'::text
WHEN "substring"(t."Field"::text, 0, 3) = '07'::text THEN 'group three'::text
ELSE NULL::text
END AS new_field,
CASE
WHEN "substring"(t."Field"::text, 0, 3) = '01'::text THEN 'subgroup a'::text
WHEN "substring"(t."Field"::text, 0, 4) = '123'::text THEN 'subgroup a'::text
WHEN "substring"(t."Field"::text, 0, 5) = '4567'::text THEN 'subgroup a'::text
WHEN "substring"(t."Field"::text, 0, 6) = '99999'::text THEN 'subgroup a'::text
WHEN "substring"(t."Field"::text, 0, 3) = '07'::text THEN 'subgroup b'::text
ELSE NULL::text
END AS another_new_field,...
有没有一种方法可以让一个 case 语句给出两个字段作为结果,因为处理的数据是相同的,只是标签不同。
Running PostgreSQL 7.x (Yeah I'm upgrading)
Example:
SELECT
CASE
WHEN "substring"(t."Field"::text, 0, 3) = '01'::text THEN 'group one'::text
WHEN "substring"(t."Field"::text, 0, 4) = '123'::text THEN 'group one'::text
WHEN "substring"(t."Field"::text, 0, 5) = '4567'::text THEN 'group two'::text
WHEN "substring"(t."Field"::text, 0, 6) = '99999'::text THEN 'group three'::text
WHEN "substring"(t."Field"::text, 0, 3) = '07'::text THEN 'group three'::text
ELSE NULL::text
END AS new_field,
CASE
WHEN "substring"(t."Field"::text, 0, 3) = '01'::text THEN 'subgroup a'::text
WHEN "substring"(t."Field"::text, 0, 4) = '123'::text THEN 'subgroup a'::text
WHEN "substring"(t."Field"::text, 0, 5) = '4567'::text THEN 'subgroup a'::text
WHEN "substring"(t."Field"::text, 0, 6) = '99999'::text THEN 'subgroup a'::text
WHEN "substring"(t."Field"::text, 0, 3) = '07'::text THEN 'subgroup b'::text
ELSE NULL::text
END AS another_new_field,...
Is there a way to have one case statement give two fields as a result as the data processed is the same it's just the label that's different.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我对 Postgre 不熟悉,但也许您可以尝试使用通用表表达式来构建一个表,该表索引您的查找条件以及组和子组的输出结果,它可能看起来像这样(当然条件可能来自实际的table as well...):
那么你只需要定义一次条件,并匹配一次就可以输出两个字段。正如 @Tom 在评论中所表达的,这种情况在 SQL 中没有得到很好的处理,所以你只剩下一个像上面这样的更“hacky”的解决方案。
此致,
I'm not familiar with Postgre, but perhaps You can try a common table expression to build a table indexing your lookup conditions and the output results for group and subgroup, which might look something like this (of course the conditions could come from an actual table as well...):
Then you only have to define the conditions once, and match them once to get both fields outputted. As expressed by @Tom in comment, this kind of scenario is not well handled in SQL, so you're left with a more "hacky" solution like the above.
Best Regards,