在MySql中使用UNION的SUM,COUNT

时间:2013-02-10 14:44:14

标签: mysql

我有一个具有以下架构的表:

DATA | CAUSE_1 | TIME_1 | CAUSE_2 | TIME_2 | CAUSE_3 | TIME_3

CAUSE.*字段(VarChar)不能包含任何字符串,如果是,则字段TIME.*为0。

我正在尝试创建一个查询,但遗憾的是没有成功,我将以这种形式显示结果:

CAUSE | TOT_TIME | N_RIPET_CAUSE,

其中:

  • CAUSE中,我列出了CAUSE_1 ... CAUSE_3
  • 中包含的内容
  • TOT_TIMETIME_1 ... TIME_3
  • 中值的总和
  • N_RIPET_CAUSECAUSE的重复次数。

我希望我解释过。

3 个答案:

答案 0 :(得分:3)

试试这个

 SELECT DATA ,CAUSE , TOT_TIME , N_RIPET_CAUSE
 FROM ( select DATA, CONCAT(`CAUSE_1`,' ',`CAUSE_2`, ' ', `CAUSE_3`) as CAUSE ,
 sum(`TIME_1` + `TIME_2` +`TIME_3`) as TOT_TIME ,
 (count(`CAUSE_1`)+count(`CAUSE_2`)+count(`CAUSE_3`)) as N_RIPET_CAUSE
 FROM your_table
 group by DATA
 ) t

SEE SQLFIDDLE DEMO

EDIT。

试试这个

     ( select DATA , `CAUSE_1` as CAUSE ,
     sum(`TIME_1` + `TIME_2` +`TIME_3`) as TOT_TIME ,
     (count(`CAUSE_1`)+count(`CAUSE_2`)+count(`CAUSE_3`)) as N_RIPET_CAUSE
     FROM Table1 
    group by DATA)
  union all
    (select DATA , `CAUSE_2` as CAUSE ,
    sum(`TIME_1` + `TIME_2` +`TIME_3`) as TOT_TIME ,
    (count(`CAUSE_1`)+count(`CAUSE_2`)+count(`CAUSE_3`)) as N_RIPET_CAUSE
    FROM Table1
    group by DATA   )
  union all

    (select DATA , `CAUSE_3` as CAUSE ,
    sum(`TIME_1` + `TIME_2` +`TIME_3`) as TOT_TIME ,
    (count(`CAUSE_1`)+count(`CAUSE_2`)+count(`CAUSE_3`)) as N_RIPET_CAUSE
    FROM Table1
    group by DATA   )

SQL DEMO HERE

修改

根据您的需要尝试

 select cause, sum(time) Tot_time, count(cause) N_Ripet_Cause
 from(
    select  cause_1 as cause, time_1 as time
    from Table1
    union all
    select  cause_2 as cause, time_2 as time
   from Table1
   union all
   select  cause_3 as cause, time_3 as time
   from Table1
 ) t
 group by cause

DEMO SQL FIDDLE

答案 1 :(得分:2)

您可以从联合选择中进行选择:

select * from
(
    select cause_1 as cause, time_1 as time from tableName
    union
    select cause_2 as cause, time_2 as time from tableName
    union
    select cause_3 as cause, time_3 as time from tableName
) as joinedValues

然后你可以从那个选择中执行任何操作。 像每个条款的数量一样:

select cause, count(cause) from
(
...
) as joinedValues
group by cause

答案 2 :(得分:0)

杰克已经出现了 - 你的桌面结构中有太多可能冗余的单元格。使用关系来消除这种情况。

数据表 的 dID |数据

instancesTable 的 ID | dID |原因| TIME

然后在两个表上使用NATURAL JOIN来提取信息;

SELECT * FROM DataTable NATURAL JOIN instancesTable WHERE dID=? LIMIT 3

此查询将返回第一个表中“数据”ID的原因和时间列表。

编辑:*可以使用dID上的 SUM(CAUSE)找到N_RIPET_CAUSE *。