如何在SQL中加入'union all'的结果

时间:2012-08-14 06:08:12

标签: mysql sql group-by union-all

我使用 union all 组合了两个表。但是,生成的数据有重复。有没有办法加入重复?

例如, union all t之后的结果表看起来像这样“:

__DAY__.....................__COUNT__
monday....................1
tuesday...................2
tuesday...................3
wednesday..............4
wednesday..............1
wednesday..............5

我希望它看起来像这样:

__DAY__.................__COUNT__
monday....................1
tuesday....................5
wednesday..............10

另外,我尝试了“按t.day,t.count分组”,但它不起作用。 而“....”仅用于格式化目的,以便进行某种缩进。

查询如下。

SELECT   t1.hour, t1.day, t1.count
FROM
(
  (SELECT hour(time(FROM_UNIXTIME( timecode)))  AS hour,
   date(FROM_UNIXTIME( timecode))  AS day,
  (FROM_UNIXTIME( timecode)) AS original, COUNT(1)  as 'count'
   FROM sampleData
  WHERE hour(time(FROM_UNIXTIME( timecode)))>=14
   GROUP BY DAY)
 union all
  (SELECT hour(time(FROM_UNIXTIME( timecode))) as hour,
   date(FROM_UNIXTIME( timecode-86400) ) AS day,
   (FROM_UNIXTIME( timecode)) AS original, COUNT(1)  as 'count'
  FROM sampleData
  WHERE hour(time(FROM_UNIXTIME( timecode)))< 14
   GROUP BY DAY)
)  t1
GROUP BY  t1.day, t1.count
HAVING COUNT(*)>0
ORDER BY t1.day

3 个答案:

答案 0 :(得分:5)

尝试这个简单的查询:

SELECT day,sum(count) FROM Table1
Group by day

See this SQLFiddle

编辑:对于您的查询,请尝试以下操作:

SELECT   t1.hour, t1.day, sum(t1.count)
FROM 
(
  (SELECT hour(time(FROM_UNIXTIME( timecode)))  AS hour,  
   date(FROM_UNIXTIME( timecode))  AS day, 
  (FROM_UNIXTIME( timecode)) AS original, COUNT(1)  as 'count'  
   FROM sampleData  
  WHERE hour(time(FROM_UNIXTIME( timecode)))>=14  
   GROUP BY DAY)   
 union all   
  (SELECT hour(time(FROM_UNIXTIME( timecode))) as hour,  
   date(FROM_UNIXTIME( timecode-86400) ) AS day,  
   (FROM_UNIXTIME( timecode)) AS original, COUNT(1)  as 'count'  
  FROM sampleData   
  WHERE hour(time(FROM_UNIXTIME( timecode)))< 14  
   GROUP BY DAY)  
)  t1  
GROUP BY  t1.day
HAVING COUNT(*)>0  
ORDER BY t1.day  

答案 1 :(得分:0)

您可以尝试分组

select DAY,sum(COUNT) as COUNT
from
( select DAY,COUNT from table1
  union all
 select DAY,COUNT from table1)a
group by a.DAY

修改

对于您的查询,

SELECT    t1.day, sum( t1.count )

.....
.....
GROUP BY  t1.day
HAVING COUNT(*)>0
ORDER BY t1.day

答案 2 :(得分:0)

按计数和仅按天计算。

SELECT   t1.hour, t1.day, sum(t1.count)   
    FROM 
    (
      (SELECT hour(time(FROM_UNIXTIME( timecode)))  AS hour,  
       date(FROM_UNIXTIME( timecode))  AS day, 
      (FROM_UNIXTIME( timecode)) AS original, COUNT(1)  as 'count'  
       FROM sampleData  
      WHERE hour(time(FROM_UNIXTIME( timecode)))>=14  
       GROUP BY DAY)   
     union all   
      (SELECT hour(time(FROM_UNIXTIME( timecode))) as hour,  
       date(FROM_UNIXTIME( timecode-86400) ) AS day,  
       (FROM_UNIXTIME( timecode)) AS original, COUNT(1)  as 'count'  
      FROM sampleData   
      WHERE hour(time(FROM_UNIXTIME( timecode)))< 14  
       GROUP BY DAY)  
    )  t1  
    GROUP BY  t1.day
    HAVING COUNT(*)>0  
    ORDER BY t1.day