在SUM子句中使用LAG或其他函数

时间:2014-01-09 02:35:22

标签: sql oracle

我正在寻找有关我一直在努力的Oracle SQL查询的一些指导。

我有一个包含时间戳和帮助台票号的数据表...

每次技术人员更改故障单或记录备注时,相应的时间戳将与故障单号一起登录数据库。我想要完成的是计算每个系列中第一次出现的票号,我不能使用distinct,因为如果技术人员在当天晚些时候再次使用票证,它将不再计算票证。请参考附图。

http://s13.postimg.org/i5gx4l4nb/sample.jpg

使用滞后函数我可以在行级别标记票证,但我不能将其添加到SUM子句中以实现我的最终目标。

CASE WHEN LAG(IPCS_AUDIT_HISTORY.ENTITYID,1) over (ORDER BY IPCS_AUDIT_HISTORY.HISTORYDATE)=IPCS_AUDIT_HISTORY.ENTITYID THEN 0 ELSE 1 END

关于采取何种方向的任何想法或想法?

SELECT
  UPPER(IPCS_PLANNER.PLANNERSURNAME || ', ' || IPCS_PLANNER.PLANNERFIRSTNAME) AS FULL_NAME,
  COUNT(DISTINCT IPCS_AUDIT_HISTORY.ENTITYID) AS TICKETS_COUNT,
  SUM(CASE WHEN LAG(IPCS_AUDIT_HISTORY.ENTITYID,1) over (ORDER BY IPCS_AUDIT_HISTORY.HISTORYDATE)=IPCS_AUDIT_HISTORY.ENTITYID THEN 0 ELSE 1 END) AS TOUCH_COUNT
FROM 
  IPCS_AUDIT_HISTORY,
  IPCS_PLANNER
WHERE
  IPCS_AUDIT_HISTORY.PLANNERID=IPCS_PLANNER.PLANNERID and
  TRUNC(IPCS_AUDIT_HISTORY.HISTORYDATE, 'IW')='30-DEC-13'
GROUP BY
  UPPER(IPCS_PLANNER.PLANNERSURNAME || ', ' || IPCS_PLANNER.PLANNERFIRSTNAME)

2 个答案:

答案 0 :(得分:1)

我可能会误解您的问题,但我相信您只需要将ROWS BETWEEN添加到SUM()

SUM(ColName) OVER(ORDER BY Col2 ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)

答案 1 :(得分:0)

更新:以这种方式尝试

SELECT full_name, 
       COUNT(DISTINCT entityid) ticket_count,
       COUNT(DISTINCT series) - COUNT(DISTINCT entityid) touch_count
  FROM
(
  SELECT plannerid, full_name, entityid, 
         rnum - ROW_NUMBER() OVER (PARTITION BY plannerid, entityid ORDER BY rnum) series
    FROM
  (  
    SELECT p.plannerid, 
           UPPER(p.plannersurname || ', ' || p.plannerfirstname) full_name,
           h.historydate, 
           h.entityid,
           ROW_NUMBER() OVER (PARTITION BY p.plannerid ORDER BY h.historydate) rnum
      FROM ipcs_audit_history h JOIN ipcs_planner p
        ON h.plannerid = p.plannerid
     WHERE h.historydate >= TO_DATE('30-DEC-13')
       AND h.historydate <  TO_DATE('30-DEC-13') + 1
  ) q
) p
 GROUP BY plannerid, full_name

示例输出:

| FULL_NAME | TICKET_COUNT | TOUCH_COUNT |
|-----------|--------------|-------------|
| DOE, JOHN |            4 |           1 |

这是 SQLFiddle 演示