将两行合二为一 - My Sql

时间:2012-06-07 10:28:09

标签: mysql sql

我找到了一些类似的帖子,但我发现它们没用。但我不知道如何将它们分组。

我想将'否'和'未设置'汇总到一行,并丢失'未设置'行。

所以:'不'='不'+'未设置'

我有这样的事情:

TEST           TestCount        Month
'Yes'          123              March
'No'           432              March
'Not Set'      645              March
'Yes'          13               April
'No'           42               April
'Not Set'      45               April
'Yes'          133              May
'No'           41               May
'Not Set'      35               May
....

我想要这样的事情:

TEST           TestCount        Month
'Yes'          423              March      (Should be  123? - @Dems)
'No'           410              March      (Should be 1077? - @Dems)
'Yes'          154              April      (Should be   13? - @Dems)
'No'           192              April      (Should be   87? - @Dems)
'Yes'          130              May        (Should be  133? - @Dems)
'No'           149              May        (Should be   76? - @Dems)

...

任何人都可以提前帮助我吗

4 个答案:

答案 0 :(得分:5)

SELECT  CASE test WHEN 'Not Set' THEN 'No' ELSE test END AS newtest,
        month, SUM(testCount)
FROM    mytable
GROUP BY
        newtest, month

答案 1 :(得分:3)

SQL Fiddle with Demo

SELECT CASE WHEN test = 'Not Set' THEN 'No' ELSE test END AS testvalue
  , SUM(testCount) as TestCount
  , month
FROM    test
GROUP BY testvalue, month

答案 2 :(得分:2)

SELECT TEST, TestCount, Month
FROM (
        (SELECT 'No' AS TEST, SUM(TestCount) AS TestCount, Month
         FROM mytable
         WHERE TEST = 'No'
           OR TEST = 'Not Set'
         GROUP BY MONTH)
      UNION
        (SELECT TEST, TestCount, Month
         FROM mytable
         WHERE TEST = 'Yes')) AS newtable
GROUP BY Month, TEST;

答案 3 :(得分:0)

SELECT TEST, TestCount, Month  
FROM   
       (SELECT 'No' AS TEST, SUM(TestCount) AS TestCount, Month  
        FROM testEntity  
        WHERE TEST = 'No' OR TEST = 'Not Set'  
        GROUP BY MONTH)  
    UNION  
       (SELECT TEST, TestCount, Month  
        FROM testEntity  
        WHERE TEST = 'Yes')  
AS newtable  
GROUP BY Month, TEST, TestCount;  

testCount也应包含在Group by子句中。