MySQL:如何计算一行中的非空字段,然后计算相同的值?
请记住,我无法标准化表格,因此我必须使用我所得到的东西。在表中,行与此类似
name | widget1 | widget2 | widget3
------+-----------+----------+----------
Joe | blue | red |
Jane | green | |
Bob | red | red | green
Susy | green | green |
我想做的是计算小部件的总数(Joe 有 2 个小部件,Jane 有 1 个等),并计算类似小部件的数量(Bob 有 3 个小部件) - 2 个红色和 1 个绿色,Susy 有 2 个小部件 - 2 个绿色等)
这是我计算小部件总数的代码:
SELECT (
SUM( IF(widget1 <> "", 1, 0) ) +
SUM( IF(widget2 <> "", 1, 0) ) +
SUM( IF(widget3 <> "", 1, 0) )
) AS totalWidgets FROM table
效果很好。但有更好的方法吗?另外,为了计算相似值的数量,我确信我可以做类似的事情,但只需检查值是否相等......但它可能会变得相当长且令人费解。
有没有更直接的方法?
Keep in mind that there's no way I can normalize the table, so I'm having to work with what I got. In the table, the rows are similar to this
name | widget1 | widget2 | widget3
------+-----------+----------+----------
Joe | blue | red |
Jane | green | |
Bob | red | red | green
Susy | green | green |
What I'd like to do is count the total number of widgets (Joe has 2 widget, Jane has 1, etc), and also count the number of similar widgets (Bob has 3 widgets - 2 red and 1 green, Susy has 2 widgets- 2 green, etc)
Here's my code to count the total number of widgets:
SELECT (
SUM( IF(widget1 <> "", 1, 0) ) +
SUM( IF(widget2 <> "", 1, 0) ) +
SUM( IF(widget3 <> "", 1, 0) )
) AS totalWidgets FROM table
Which works fine. But is there a better way to do this? Also, to count the number of similar of values, I'm sure I can so something similar but just check if the values are equal... but it could get pretty long and convoluted.
Is there a more direct approach?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
尚未测试,但它应该可以工作
All on one line
q
是我们的规范化“表”(不是真正的表,但它看起来有点像)。以这种方式查看我们的规范化表
不知道你怎么称呼它,我认为它是一个子查询。 (我已经使用 MySQL 多年了,但我仍然不知道正确的名称)
Have not tested, but it should work
All on one line
q
is our normalized "table" (not really a table, but it kinda looks like one).See our normalized table this way
Not sure what you call it, I think it is a subquery. (I have used MySQL for years and I still don't know the proper names)