我想查询oracle db以获取带有多个case子句的计数

时间:2014-10-08 09:01:22

标签: sql oracle

这是我尝试的查询:

SELECT DISTINCT(
  ( select distinct (
      (SELECT COUNT(*)  
       FROM PROCESS 
       WHERE STARTDATE > sysdate - INTERVAL '7' DAY) - 
      (SELECT COUNT(*) 
       FROM PROCESS 
       WHERE STARTDATE > sysdate - INTERVAL '14' DAY AND 
             STARTDATE < sysdate - INTERVAL '7' DAY)
  )as c3
  from process) /
  ( SELECT (CASE WHEN COUNT(*)=0 THEN (
      SELECT (case WHEN COUNT(*)=0 THEN 1  ELSE COUNT(*) end) 
      FROM PROCESS 
      WHERE STARTDATE > SYSDATE - INTERVAL '7' DAY  ) 
    ELSE COUNT(*) END)  
   FROM PROCESS 
   WHERE STARTDATE > SYSDATE - INTERVAL '14' DAY AND
         STARTDATE < SYSDATE - INTERVAL '7' DAY )
) AS ORDER_VOLUME FROM PROCESS;

但我收到此错误:

ORA-00937: not a single-group group function
00937. 00000 -  "not a single-group group function"
*Cause:    
*Action:
Error at Line: 1 Column: 295

任何人都可以帮我解决这个问题吗?

这是我想要的

1)获取STARTDATE&gt;的计数SYSDATE - INTERVAL&#39; 14&#39;一天和              STARTDATE&lt; SYSDATE - INTERVAL&#39; 7&#39;天 , 2)如果计数为0则      得到STARTDATE&gt;的计数SYSDATE - INTERVAL&#39; 14&#39;一天和              STARTDATE&lt; SYSDATE - INTERVAL&#39; 7&#39;天 , 否则设置该计数

如果在步骤2中检索的计数也为0,则将计数设置为1 否则设置检索的计数

2 个答案:

答案 0 :(得分:0)

这部分在'/'

之后
SELECT  (
**--**CASE  WHEN COUNT()=0 THEN (
    SELECT  (
    case    WHEN COUNT()=0 THEN 1 
        ELSE    COUNT() 
    end ) 
FROM    PROCESS 
WHERE   STARTDATE > SYSDATE - INTERVAL '7' DAY ) 
ELSE    COUNT() 
END ) 

你不觉得应该有一个选择我把它标记为' - '你没有选择哪个错误或只是删除那个括号并尝试

SELECT  
CASE    WHEN COUNT()=0 THEN (
    SELECT  (
    case    WHEN COUNT()=0 THEN 1 
        ELSE    COUNT() 
    end ) 
FROM    PROCESS 
WHERE   STARTDATE > SYSDATE - INTERVAL '7' DAY ) 
ELSE    COUNT() 
END 
FROM    PROCESS** 

答案 1 :(得分:0)

对我来说这看起来像是一个Oracle错误。该查询在语法上似乎是正确的。

然而,您似乎并不确切地知道自己在做什么。这个陈述看起来很奇怪DISTINCT两次,当你人为地为表进程中的记录数重复一个值时,这完全没有意义。

如果错误无法阻止,那么这就是您的查询所做的事情:

select
  (count_last_week - count_week_before_last_week) / 
  case 
    when count_week_before_last_week > 0 then  count_week_before_last_week
    when count_last_week > 0 then              count_last_week
    else                                       1
  end as order_volume
from
(
  select 
    sum(case when startdate > sysdate - interval '7' day then 1 end) as count_last_week,
    sum(case when startdate > sysdate - interval '14' day and startdate < sysdate - interval '7' day then 1 end) as count_week_before_last_week
  from process
);

检查,如果这是您真正想要的,并在必要时修改此查询。

顺便说一句:请注意,您有startdate > sysdate - interval '7' daystartdate < sysdate - interval '7' day但没有startdate = sysdate - interval '7' day。另外:您是否故意考虑时间,还是宁愿使用trunc(startdate)和trunc(sysdate)?