如何从MySQL中的多列值中获取唯一值?

huangapple go评论219阅读模式
英文:

How to get unique values from multiple-column values in MySQL?

问题

stf_invld_a stf_invld_b stf_invld_c stf_invld_d stf_invld
21,22 23,25 24 26,27 21,22,23,24,25,26,27
英文:

I have a query result using the group_concat function in MySQL like below.

stf_invld_a stf_invld_b stf_invld_c stf_invld_d
21,22,0,0 21,23,25,0 21,24,25,0 24,26,27,0

Now I need a query where each column value will get only once, zero values will be skipped, and need another column with unique values.

stf_invld_a stf_invld_b stf_invld_c stf_invld_d stf_invld
21,22 23,25 24 26,27 21,22,23,24,25,26,27

答案1

得分: 1

广义而言,您应该使用GROUP_CONCATDISTINCTCASE表达式。类似这样:

SELECT  -- 在GROUP BY中出现的某些列
    GROUP_CONCAT(DISTINCT CASE WHEN a != 0 THEN a END) AS stf_invld_a
FROM yourTable
GROUP BY -- 某些列
英文:

Broadly speaking, you should use GROUP_CONCAT along with DISTINCT and a CASE expression. Something like:

<!-- language: sql -->

SELECT  -- certain columns which appear in GROUP BY
    GROUP_CONCAT(DISTINCT CASE WHEN a != 0 THEN a END) AS stf_invld_a
FROM yourTable
GROUP BY -- certain columns

huangapple
  • 本文由 发表于 2023年7月6日 13:53:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76625876.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定