MySQL: Getting count and sum of integer values in multiple columns

我们两清 提交于 2020-01-16 01:15:45

问题


Ok so my requirement is fairly simple. I have a table like so.

images     |     videos      |      reviews
--------------------------------------------------
0          |     2           |       1
4          |     5           |       0
11         |     1           |       4
0          |     1           |       7

I need to write a query that counts the rows in each column that is not equal to 0, and also that gives the actual sum of the numbers in the columns. So the result will look something like this.

Columns        |     Counts      |      Sum
----------------------------------------------------
images         |     2           |      15
videos         |     4           |      9
reviews        |     3           |      13

Is this directly possible with SQL? I don't want to do the sum on the application level. So far I have written this query and it works fine, just without the sum part.

SELECT 'images', SUM(images != 0)
FROM dpsreport where publisherId = 91
UNION
SELECT 'videos', SUM(videos != 0)
FROM dpsreport where publisherId = 91
UNION
SELECT 'reviews', SUM(reviews != 0)
FROM dpsreport where publisherId = 91;

Note that SUM in the query gives me the count of the rows, not the actual sum, as in mathematical addition.


回答1:


I think this does what you want:

SELECT 'images' as `columns`, SUM(images <> 0) as counts, SUM(images) as `sum`
FROM dpsreport where publisherId = 91
UNION ALL
SELECT 'videos', SUM(videos <> 0), SUM(videos)
FROM dpsreport where publisherId = 91
UNION ALL
SELECT 'reviews', SUM(reviews <> 0), SUM(reviews)
FROM dpsreport where publisherId = 91;

Notes:

  • The SQL standard for not equals is <> rather than != (although many databases support both).
  • Use UNION ALL rather than UNION, to avoid the overhead of removing duplicates (which is negligible in this case).


来源:https://stackoverflow.com/questions/33435290/mysql-getting-count-and-sum-of-integer-values-in-multiple-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!