4

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

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_TIME中的值的总和中TIME_1 ... TIME_3
  • N_RIPET_CAUSE每个的重复次数中CAUSE

我希望我解释了。

4

4 回答 4

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

查看 SQLFIDDLE 演示

编辑。

尝试这个

     ( 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 演示在这里

编辑:

根据您的需要试试这个

 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

演示 SQL 小提琴

于 2013-02-10T15:06:23.363 回答
3

如果您无法更改表结构,那么为了获得此结果,您需要将列取消透视为行。

MySQL 没有 unpivot 函数,但这可以使用UNION ALL查询来完成。然后,您可以将聚合应用于这些值以获得最终结果:

select cause, sum(time) Tot_time, count(cause) N_Ripet_Cause
from
(
  select data, cause_1 as cause, time_1 as time
  from yourtable
  union all
  select data, cause_2 as cause, time_2 as time
  from yourtable
  union all
  select data, cause_3 as cause, time_3 as time
  from yourtable
) src
group by cause
于 2013-02-10T15:01:30.977 回答
2

您可以像这样从 union select 中进行选择:

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
于 2013-02-10T14:59:24.630 回答
0

杰克是对的——你的表格结构中有太多可能冗余的单元格。使用关系来消除此类事件。

数据 表 dID | 数据

实例表 ID | 身份证 | 原因 | 时间

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

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

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

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

于 2013-02-10T14:53:53.533 回答