将查询更改为汇总或汇总数据

时间:2017-09-14 17:47:23

标签: sql sum having

我有一个SQL查询工作正常,但我现在需要更改它以总结数据,我不知道如何去做 -

SELECT store, tintermodel, tinterserial, eventdetails, trunc(datetime), COUNT(*)
FROM tinter_events
WHERE tintermodel = 'FM 8000DE'  
AND (datetime >= to_timestamp('2017-05-01', 'YYYY-MM-DD') 
AND datetime < to_timestamp('2017-08-31', 'YYYY-MM-DD'))
AND function = 'Set Colorant Level'
AND eventdetails IN ('R3[128]', 'G2[128]', 'W1[345]', 'Y3[512]', 'N1[185]', 
'R4[128]', 'L1[128]', 'B1[550]', 'B1[512]', 'Y1[128]', 'R2[185]')
GROUP BY store, tintermodel, tinterserial, eventdetails, trunc(datetime) 
HAVING COUNT(*) > 1
ORDER BY store, tinterserial, eventdetails, trunc(datetime);

这样做可以让我计算出特定型号(按序列号)填写的任何日期(“设置着色剂级别”),一天不止一次。这为我提供了每个日期的显示。

但是现在我需要通过商店为每个着色剂总数(也就是SUBSTR(eventdetails,1,2))总结一下。换句话说,左边的商店列表和每个着色剂的列数只有的总数,每个着色剂被填充多次。

我不知道该如何处理,因为我已经计算过只会让我每天在特定型号/系列上多次填充着色剂。或许某种SUM / SUMIF?或者是一个子选择?

1 个答案:

答案 0 :(得分:1)

您可以获得基本数据:

SELECT store, SUBSTR(eventdetails, 1, 2) as colorant, COUNT(*) as numdays
FROM (SELECT store, tintermodel, tinterserial, eventdetails, trunc(datetime), COUNT(*)
      FROM tinter_events
      WHERE tintermodel = 'FM 8000DE' AND 
            datetime >= to_timestamp('2017-05-01', 'YYYY-MM-DD') AND
            datetime < to_timestamp('2017-08-31', 'YYYY-MM-DD') AND
            function = 'Set Colorant Level' AND
            eventdetails IN ('R3[128]', 'G2[128]', 'W1[345]', 'Y3[512]', 'N1[185]', 
'R4[128]', 'L1[128]', 'B1[550]', 'B1[512]', 'Y1[128]', 'R2[185]')
      GROUP BY store, tintermodel, tinterserial, eventdetails, trunc(datetime) 
      HAVING COUNT(*) > 1
     ) t
GROUP BY store, SUBSTR(eventdetails, 1, 2);

这会产生您想要的数据,但会产生三列。您可以使用条件聚合来转动它:

SELECT store,
       SUM(CASE WHEN SUBSTR(eventdetails, 1, 2) = 'R3' THEN 1 ELSE 0 END) as R3,
       SUM(CASE WHEN SUBSTR(eventdetails, 1, 2) = 'G2' THEN 1 ELSE 0 END) as G2,
       SUM(CASE WHEN SUBSTR(eventdetails, 1, 2) = 'W1' THEN 1 ELSE 0 END) as W1,
       . . .
FROM (SELECT store, tintermodel, tinterserial, eventdetails, trunc(datetime), COUNT(*)
      FROM tinter_events
      WHERE tintermodel = 'FM 8000DE' AND 
            datetime >= to_timestamp('2017-05-01', 'YYYY-MM-DD') AND
            datetime < to_timestamp('2017-08-31', 'YYYY-MM-DD') AND
            function = 'Set Colorant Level' AND
            eventdetails IN ('R3[128]', 'G2[128]', 'W1[345]', 'Y3[512]', 'N1[185]', 
'R4[128]', 'L1[128]', 'B1[550]', 'B1[512]', 'Y1[128]', 'R2[185]')
      GROUP BY store, tintermodel, tinterserial, eventdetails, trunc(datetime) 
      HAVING COUNT(*) > 1
     ) t
GROUP BY store;