sum field value after using if and count in sql

时间:2017-08-04 12:48:40

标签: php mysql sql mysqli

I Get All Count Value By Following Query But Now I Need Sum Of all This count value that i get. How can i do thAT ?

SELECT pkg_name, IF(COUNT(*)<=2, COUNT(*), 2) AS total from packages GROUP by pkg_name

2 个答案:

答案 0 :(得分:0)

You can wrap this query into another SELECT, e.g:

SELECT SUM(total) AS `sum`
FROM (SELECT pkg_name, IF(COUNT(*)<=2, COUNT(*), 2) AS total 
      FROM packages 
      GROUP by pkg_name) a

答案 1 :(得分:0)

you can use extra select for get data from drive table so you can sum all value from drive table

SELECT sum(total) as total_value
FROM (SELECT pkg_name, IF(COUNT(*)<=2, COUNT(*), 2) AS total 
      FROM packages 
      GROUP by pkg_name) final_table