如果没有结果则返回零

时间:2014-04-22 16:51:53

标签: sql oracle

我在构建查询时遇到了麻烦,我觉得这很简单......

我有一个简单的表格,我在那里做一个简单的计数,当我用日期过滤结果时,我希望零没有行,而不是没有结果。

例如:

select APP_ID as APPLI, count(ID) as NB 
from ARCHIVE 
where GROUP_ID = 'Sample'
GROUP BY APP_ID 

返回

A   560
B   1,178
C   9
D   643
E   4

select APP_ID as APPLI, count(ID) as NB 
from ARCHIVE 
where GROUP_ID = 'Sample' and TIMESTAMP > TO_DATE('01/01/2014','dd/mm/yyyy') 
GROUP BY APP_ID 

返回

B   40
D   82
E   4

我想要

A   0
B   40
C   0
D   82
E   4

一些示例数据:

ID              APP_ID  TIMESTAMP
ARCH_1/20/216       A   2010-12-16
ARCH_1/20/218       A   2010-12-16
ARCH_1/20/219       A   2010-12-16
ARCH_1/40/28        A   2011-02-09
ARCH_1/40/29        A   2011-02-09
ARCH_1/40/30        A   2011-02-09
ARCH_1/260/9012     B   2014-04-19
ARCH_1/260/7093     B   2014-04-12
ARCH_1/260/8996     B   2014-04-19
ARCH_1/44/61        C   2011-09-12
ARCH_1/44/62        C   2011-09-13
ARCH_1/260/8382     D   2014-04-16
ARCH_1/260/6872     D   2014-04-11
ARCH_1/260/6271     D   2014-04-08
ARCH_1/260/8607     D   2014-04-17
ARCH_1/260/8998     E   2014-04-19
ARCH_1/260/9011     E   2014-04-19

编辑:我使用的是Oracle SQL

3 个答案:

答案 0 :(得分:1)

为了完成这项工作,您首先需要一个(明确的)所有 ID列表。在这种情况下,首选子查询:

SELECT Archive_List.app_id, COALESCE(COUNT(), 0) as NB
FROM (SELECT DISTINCT app_id
      FROM Archive) Archive_List
LEFT JOIN Archive
       ON Archive.app_id = Archive_List.app_id
          AND Archive.group_id = 'Sample'
          AND Archive.timestamp >= CAST('2014-01-01' as DATE)
GROUP BY Archive_List.app_id

如果timestamp实际 指示的类型(顺便说一下,这是列的可怕的名称),那么您应该使用{{1因此,您可以在午夜设置任何行 该语句适用于大多数/所有RDBMS

答案 1 :(得分:0)

试试这个:

select A1.APP_ID as APPLI, NVL(count(A2.ID),0) as NB 
from ARCHIVE A1 LEFT JOIN
     ARCHIVE A2 on A1.APP_ID=A2.APP_ID
where A1.GROUP_ID = 'Sample' and A1.TIMESTAMP > TO_DATE('01/01/2014','dd/mm/yyyy') 
GROUP BY A1.APP_ID 

答案 2 :(得分:0)

select 
A2.APP_ID as APPLI,
NVL(count(A1.ID),0) as NB 
from ARCHIVE A1
RIGHT JOIN ARCHIVE A2 on A1.APP_ID = A2.APP_ID
where A1.GROUP_ID = 'Sample' and A1.TIMESTAMP > TO_DATE('01/01/2014','dd/mm/yyyy') 
GROUP BY A2.APP_ID 

这个怎么样?


WITH X AS(
SELECT DISTINCT
APP_ID
from
ARCHIVE)

SELECT
X.APP_ID
,COALESCE(count(A.ID),0)
from
X
left join ARCHIVE A on X.APP_ID = A.APP_ID
where
A1.GROUP_ID = 'Sample' and A1.TIMESTAMP > TO_DATE('01/01/2014','dd/mm/yyyy') 
group by
X.APP_ID