Sum在我的查询中乘以结果

时间:2014-02-14 16:23:36

标签: mysql sum

我正在进行查询,并且很好地展示了我想要的所有内容:

SELECT prog.cod_go, prog.data, prog.item, prog.tempoexposicao
FROM tb_programacao prog 
JOIN tb_go go ON go.cod_go = prog.cod_go where go.cod_go = '1' 
AND go.equi_func1_mat = '0735'
AND prog.data = '2014-01-24' 
GROUP BY prog.data,prog.item

result:
cod_go | data      | item | tempoexposicao
1      |2014-01-24 | 10   | 00:00:30
1      |2014-01-24 | 11   | 00:00:30
1      |2014-01-24 | 12   | 00:00:30
1      |2014-01-24 | 13   | 00:00:30
1      |2014-01-24 | 14   | 00:00:30
1      |2014-01-24 | 8    | 00:00:30
1      |2014-01-24 | 9    | 00:00:30

之后我尝试了所有这个“tempoexposicao”字段的总和

SELECT SEC_TO_TIME( SUM(TIME_TO_SEC(temp.soma))) AS soma_tudo, temp.cod_go, temp.data, temp.item 
FROM ( SELECT SUM( prog.tempoexposicao) AS 'soma', prog.cod_go, prog.data, prog.item 
FROM tb_programacao prog 
JOIN tb_go go ON go.cod_go = prog.cod_go where go.cod_go = '1'
AND go.equi_func1_mat = '0735' 
AND prog.data = '2014-01-24' 
GROUP BY prog.data,prog.item ) AS temp

result:
soma_tudo | cod_go | data      | item
00:42:00  | 1      |2014-01-24 | 10

我期待00:03:30而不是00:42:00,我不能做这个子查询?

3 个答案:

答案 0 :(得分:0)

这是您的基本查询:

SELECT prog.cod_go, prog.data, prog.item, prog.tempoexposicao
FROM tb_programacao prog JOIN
    tb_go go
    ON go.cod_go = prog.cod_go
where go.cod_go = '1' AND
     go.equi_func1_mat = '0735' AND
     prog.data = '2014-01-24' 
GROUP BY prog.data, prog.item;

select中有两列不属于group byprog.itemprog.tempoexposicao的列。这些列的值来自任意匹配行。

此版本应提供一致的结果:

SELECT prog.cod_go, prog.data, min(prog.item) as item, min(prog.tempoexposicao) as tempoexposicao
FROM tb_programacao prog JOIN
    tb_go go
    ON go.cod_go = prog.cod_go
where go.cod_go = '1' AND
     go.equi_func1_mat = '0735' AND
     prog.data = '2014-01-24' 
GROUP BY prog.data, prog.item;

答案 1 :(得分:0)

SELECT  SEC_TO_TIME( SUM(TIME_TO_SEC(temp.tempoexposicao))) AS soma_tudo,
temp.cod_go,
temp.data,
temp.item 
FROM(
SELECT
prog.cod_go,
prog.data,
prog.item,
prog.tempoexposicao
FROM tb_programacao prog
JOIN tb_go go ON go.cod_go = prog.cod_go
where go.cod_go = '1'
and go.equi_func1_mat = '0735'
AND prog.data = '2014-01-24'
group by  prog.data,prog.item) AS temp

全部工作!

答案 2 :(得分:0)

有效 我在子查询中进行连接然后将所有内容作为动态表进行求和 谢谢大家

SELECT  SEC_TO_TIME( SUM(TIME_TO_SEC(temp.tempoexposicao))) AS soma_tudo,
temp.cod_go,
temp.data,
temp.item 
FROM(
SELECT
prog.cod_go,
prog.data,
prog.item,
prog.tempoexposicao
FROM tb_programacao prog
JOIN tb_go go ON go.cod_go = prog.cod_go
where go.cod_go = '1'
and go.equi_func1_mat = '0735'
AND prog.data = '2014-01-24'
group by  prog.data,prog.item) AS temp