SUM CASE从连接表而不是主表添加

时间:2018-03-01 09:11:01

标签: mysql

我有一个从客户检索的查询:

  • 他的门票上花费的时间总和(每张门票可以有一次或多次干预)
  • 平均解决时间
  • 每张票的类别

查询:

SELECT SUM(f.duree) as total_time, SUM(timestampdiff(second, t.datec, t.date_close))/COUNT(distinct t.rowid) as average_resolution, COUNT(distinct t.rowid) as tickets, 
                SUM( CASE t.category_code WHEN 'WITHOUT_MAINTENANCE' THEN 1 ELSE 0 END) as sin_mantenimiento,
                SUM( CASE t.category_code WHEN 'WITH_MAINTENANCE' THEN 1 ELSE 0 END) as con_mantenimiento,
                SUM( CASE t.category_code WHEN 'WITH_BILLABLE_MAINTENANCE' THEN 1 ELSE 0 END) as con_mantenimiento_facturable,
                SUM( CASE t.category_code WHEN 'NO_BILLABLE_COASER_WARRANTY' THEN 1 ELSE 0 END) as no_facturable_garantia_coaser,
                SUM( CASE t.category_code WHEN 'OFERTADO' THEN 1 ELSE 0 END) as ofertado
                FROM llx_ticketsup as t
                JOIN llx_element_element as ee on ee.fk_source = t.rowid
                JOIN llx_fichinter as f on f.rowid = ee.fk_target
                WHERE t.fk_soc = 47 AND t.fk_statut = 8

其中

  • llx_ticketsup是主要门票表
  • llx_fichinter是存储故障单干预的表格
  • llx_element_element是门票和干预之间的表格

我的问题是,如果一张票有多于一次的干预,就类别类型的总和知道有多少来自这个类别而有多少来自另一个,它总结干预而不是票。例如,如果查询返回2张票,并且共有6次干预,则返回6个类别为WITHOUT_MAINTENANCE的票证,而不是2张类别为WITHOUT_MAINTENANCE的票证。

什么错了?感谢。

1 个答案:

答案 0 :(得分:0)

Nothings'错误'的预期行为尝试使用子查询来获取持续时间。像

这样的东西
SELECT (select sum(f.duree) from llx_fichinter as f on f.rowid = ee.fk_target) as total_time, SUM(timestampdiff(second, t.datec, t.date_close))/COUNT(distinct t.rowid) as average_resolution, COUNT(distinct t.rowid) as tickets, 
                SUM( CASE t.category_code WHEN 'WITHOUT_MAINTENANCE' THEN 1 ELSE 0 END) as sin_mantenimiento,
                SUM( CASE t.category_code WHEN 'WITH_MAINTENANCE' THEN 1 ELSE 0 END) as con_mantenimiento,
                SUM( CASE t.category_code WHEN 'WITH_BILLABLE_MAINTENANCE' THEN 1 ELSE 0 END) as con_mantenimiento_facturable,
                SUM( CASE t.category_code WHEN 'NO_BILLABLE_COASER_WARRANTY' THEN 1 ELSE 0 END) as no_facturable_garantia_coaser,
                SUM( CASE t.category_code WHEN 'OFERTADO' THEN 1 ELSE 0 END) as ofertado
                FROM llx_ticketsup as t
                JOIN llx_element_element as ee on ee.fk_source = t.rowid

                WHERE t.fk_soc = 47 AND t.fk_statut = 8

如果不起作用,请将样本数据和预期结果作为文本添加到问题中,以便我们可以使用它。