选择具有多个列的行数,最少列数为1

时间:2015-01-19 16:13:45

标签: oracle group-by min

Table Structure:
CASENUM NUMBER(15,0)    No
DESCRIPTION VARCHAR2(150 BYTE)  Yes
COMPLETED   VARCHAR2(5 BYTE)    Yes
USERID  VARCHAR2(10 BYTE)   Yes
TRIGGERDATE DATE    Yes
DOCUMENTID  VARCHAR2(10 BYTE)   Yes
ROWSEQ  NUMBER  Yes
UPDATEDON   DATE    Yes
TRIGTYPE    VARCHAR2(5 BYTE)    Yes

我需要选择每个触发类型的病例数,每个日期 如果同一案件有两个类似的触发器,那么它应该只计算一次,并且应该在最早的日期计算。

 SELECT 
  TRIGTYPE                          ,
  COUNT(TRIGTYPE) AS PENDINGTRIGGERS,
  TRUNC(TRIGGERDATE)
   FROM TBLNABTRIGGERDETAILS 
   WHERE
 COMPLETED     ='false'
AND TRIGTYPE     IS NOT NULL
and TRIGGERDATE > '17-JAN-2015'
GROUP BY TRUNC(TRIGGERDATE), TRIGTYPE
ORDER BY TRUNC(TRIGGERDATE), TRIGTYPE;

输出

TRIGTYPE PENDINGTRIGGERS        TRUNC(TRIGGERDATE)        
-------- ---------------------- ------------------------- 
DOC      1                      17-01-15                  
NEW      3                      17-01-15                  
DOC      2                      18-01-15                  
FUP      1                      18-01-15                  
REJ      1                      18-01-15     

选择了5行

表中的数据

CASENUM COMPLETED   TRIGGERDATE TRIGTYPE
111953805   false   18-01-15    REJ
111953805   false   18-01-15    FUP
111953805   false   18-01-15    DOC
111953805   false   18-01-15    DOC
111953805   false   17-01-15    DOC
111953746   false   17-01-15    NEW
111953805   false   17-01-15    NEW
111953804   false   17-01-15    NEW

我想只计算一次DOC,它应该在1月17日之前。 这可以使用单个查询吗?

预期产出:

TRIGTYPE PENDINGTRIGGERS        TRUNC(TRIGGERDATE)        
-------- ---------------------- ------------------------- 
DOC      1                      17-01-15                  
NEW      3                      17-01-15                          
FUP      1                      18-01-15                  
REJ      1                      18-01-15     

1 个答案:

答案 0 :(得分:1)

如果我理解正确,如果它的CASENUM + TRIGTYPE等于某些较旧记录的CASENUM + TRIGTYPE,则您希望不考虑行。因此,您应该使用MINUS或反连接来过滤这些记录。例如:

SELECT 
  TRIGTYPE                          ,
  COUNT(TRIGTYPE) AS PENDINGTRIGGERS,
  TRUNC(TRIGGERDATE)
FROM (
  select t1.* 
  from TBLNABTRIGGERDETAILS t1
  left outer join TBLNABTRIGGERDETAILS t2
    on (t1.casenum = t2.casenum and
        t1.trigtype = t2.trigtype and
        t1.triggerdate > t2.triggerdate)
  where t2.triggerdate is null)
WHERE
 COMPLETED = 'false'
 AND TRIGTYPE IS NOT NULL
 and TRIGGERDATE > '17-JAN-2015'
GROUP BY TRUNC(TRIGGERDATE), TRIGTYPE
ORDER BY TRUNC(TRIGGERDATE), TRIGTYPE;

P.S。它假设没有两个具有相同日期的相同事件。你应该调整连接条件是错的。