我有一个具有以下架构的表:
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
的重复次数。我希望我解释过。
答案 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
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 )
修改强>
根据您的需要尝试
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
答案 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 *。