当特定字段不存在数据时如何获得零

时间:2013-07-10 11:47:36

标签: sql oracle

表ABCD

   Group1  Class
      C1    A
      C2    A
      C3    B
      C4    C
      C1    A 

我在这里有桌子,我试图得到以下内容 结果

输出:(使用表ABCD格式需要

Group1  Class   Count
C1        A         2
C1        B         0
C1        C         0
C2        A         1
C2        B         0
C2        C         0
C3        A         0
C3        B         0
C3        C         1

我想在sql中使用查询来实现这一点。提前谢谢你,我对oracle的查询非常新,所以请帮我解决一下。

4 个答案:

答案 0 :(得分:0)

这适用于sql server

SELECT O.*
    ,CASE WHEN I.[Group1] IS NULL THEN 0 ELSE 1 END AS Cnt
FROM Table1 I RIGHT JOIN 
(
    SELECT DISTINCT T1.[Group1],T2.[Class] FROM Table1 T1
    CROSS JOIN  Table1 T2
) O ON I.[Group1] = O.[Group1] AND I.[Class] = O.[Class]

DEMO

修改

SELECT O.*
    ,SUM(CASE WHEN I.[Group1] IS NULL THEN 0 ELSE 1 END) AS Cnt
FROM Table1 I RIGHT JOIN 
(
    SELECT DISTINCT T1.[Group1],T2.[Class] FROM Table1 T1
    CROSS JOIN  Table1 T2
) O ON I.[Group1] = O.[Group1] AND I.[Class] = O.[Class]
GROUP BY O.[Group1],O.[Class]

UPDATED DEMO

答案 1 :(得分:0)

我不确定我是否理解你的问题,但我认为你想要这样的事情:

with all_combinations as (
  select distinct g.group1, c.class
  from (
    select group1
    from foobar
  ) g
    cross join (
      select class
      from foobar
  ) c
) 
select ac.group1, ac.class, count(f.group1)
from all_combinations ac
  left join foobar f on f.group1 = ac.group1 and f.class = ac.class
group by ac.group1, ac.class
order by ac.group1, ac.class

SQLFiddle演示:http://sqlfiddle.com/#!4/9be9f/1

答案 2 :(得分:0)

您可以使用以下查询来获取结果。这会创建每个group1和每个class的列表。获得该列表后,您就可以计算原始表中的匹配数量:

select s.group1, 
  s.class,
  count(d.class) tot
from 
(
  select distinct a.group1, c.class
  from abcd a
  cross join 
  (
    select distinct class
    from abcd
  ) c
) s
left join abcd d
  on s.group1 = d.group1
  and s.class = d.class
group by s.group1, s.class
order by s.group1, s.class;

请参阅SQL Fiddle with Demo

答案 3 :(得分:0)

WITH  grp AS (
        SELECT DISTINCT grp AS grp FROM abcd
        )
,  cls AS (
        SELECT DISTINCT cls AS cls FROM abcd
        )
SELECT g.grp, c.cls
        , COALESCE(a.cnt, 0) AS the_count
FROM grp g
FULL OUTER JOIN cls c ON 1=1
LEFT JOIN (
        SELECT DISTINCT grp, cls, COUNT(*) as cnt
        FROM abcd
        GROUP BY grp,cls
        ) a ON a.grp = g.grp AND a.cls = c.cls
ORDER BY g.grp ,c.cls
        ;