MySQL 跨列的不同值

发布于 2024-12-07 03:51:53 字数 457 浏览 0 评论 0原文

我有下表:

id    lb     rb     ls     rs     ch     bk     ot
 1  10000  10001  10001  10001  10001  10001  10000
 2      0  10000      0  10001      0  10000      0
 3      0      0  10000  10001  10000      0      0
 4      0      0      0  10000      0      0      0
 5      0      0      0  10000      0      0      0

我希望能够获得所有列(不包括 0)的总不同值,因此结果如下:

Code   Qty
10000    8
10001    7

最简单/最好的方法是什么?

谢谢,斯图

I have the following table:

id    lb     rb     ls     rs     ch     bk     ot
 1  10000  10001  10001  10001  10001  10001  10000
 2      0  10000      0  10001      0  10000      0
 3      0      0  10000  10001  10000      0      0
 4      0      0      0  10000      0      0      0
 5      0      0      0  10000      0      0      0

I want to be able to get the total distinct values across all columns (excluding 0) so the result is as such:

Code   Qty
10000    8
10001    7

What's the easiest/best way to do this?

Thanks, Stu

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

姜生凉生 2024-12-14 03:51:53

您可以

SELECT col1, COUNT(*)
FROM
  (
  SELECT lb AS col1
  FROM table
    UNION ALL 
  SELECT rb
  FROM table
    UNION ALL ... etc
  ) a
WHERE col1 != 0
GROUP BY col1

WHERE col1 != 0 添加到 UNIONSELECT 中,而不是添加 WHERE field_name !=0 >

You can do

SELECT col1, COUNT(*)
FROM
  (
  SELECT lb AS col1
  FROM table
    UNION ALL 
  SELECT rb
  FROM table
    UNION ALL ... etc
  ) a
WHERE col1 != 0
GROUP BY col1

Instead of WHERE col1 != 0 you can add WHERE field_name !=0 to each SELECT in UNION

还给你自由 2024-12-14 03:51:53
SELECT code     AS Code
     , SUM(cnt) AS Qty
FROM
  (   SELECT lb AS code
           , COUNT(*) AS cnt
      FROM TableX
      GROUP BY lb        
  UNION ALL
      SELECT rb AS code
           , COUNT(*) AS cnt
      FROM TableX
      GROUP BY rb
  UNION ALL        
    ...
  UNION ALL
      SELECT ot AS code
           , COUNT(*) AS cnt
      FROM TableX
      GROUP BY ot
  ) AS tmp
GROUP BY code
SELECT code     AS Code
     , SUM(cnt) AS Qty
FROM
  (   SELECT lb AS code
           , COUNT(*) AS cnt
      FROM TableX
      GROUP BY lb        
  UNION ALL
      SELECT rb AS code
           , COUNT(*) AS cnt
      FROM TableX
      GROUP BY rb
  UNION ALL        
    ...
  UNION ALL
      SELECT ot AS code
           , COUNT(*) AS cnt
      FROM TableX
      GROUP BY ot
  ) AS tmp
GROUP BY code
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文