MySQL总和两个COUNT语句

时间:2012-03-19 18:33:00

标签: mysql count sum

我知道这有一个愚蠢的解决方案,但是,对不起,我有点困惑。

我有两个SELECT COUNT语句。例如:

声明1

SELECT COUNT(softwareone) AS totalcount 
FROM my_table WHERE softwareone LIKE '%typeone%'

totalcount = 3 _

声明2

SELECT COUNT(softwaretwo) AS totalcount 
FROM my_table WHERE softwaretwo LIKE '%typeone%'

totalcout = 1

我想将两个总和相加得到totalcount = 4.还有办法吗?

注意:“softwareone”和“softwaretwo”列中的软件类型属于同一类型(相同值)。

感谢所有人。

2 个答案:

答案 0 :(得分:4)

一种方法是写:

SELECT SUM(CASE WHEN softwareone LIKE '%typeone%'
                 AND softwaretwo LIKE '%typeone%'
                THEN 2
                ELSE 1
            END
          ) AS "totalcount"
  FROM my_table
 WHERE softwareone LIKE '%typeone%'
    OR softwaretwo LIKE '%typeone%'
;

当满足两个条件时,CASE ... END表达式将评估为2(如果softwareonesoftwaretwo都是LIKE '%typeone%',那么行计数两次),1只有其中一个。因此,SUM(CASE ... END)给出满足一个条件的总行数,加上满足另一个条件的行总数。

答案 1 :(得分:3)

您可以使用

Select l1.totalcount + l2.totalcount FROM 
(SELECT COUNT(softwareone) AS totalcount 
FROM my_table WHERE softwareone LIKE '%typeone%') as l1,
(SELECT COUNT(softwaretwo) AS totalcount 
FROM my_table WHERE softwaretwo LIKE '%typeone%') as l2