我有以下选择:
SELECT
COALESCE (opened.ano, closed.ano) AS ano,
COALESCE (opened.mes, closed.mes) AS mes,
COALESCE (opened.cnt, 0) AS opened_cases,
COALESCE (closed.cnt, 0) AS closed_cases
FROM
(
SELECT
YEAR (OPEN_DATE) AS ano,
MONTH (OPEN_DATE) AS mes,
COUNT (*) AS cnt
FROM
TABLE1,
TABLE2
WHERE
TABLE1.USERNAME = TABLE2.USERNAME
AND TABLE2.GROUP = 'SUPPORT'
GROUP BY
YEAR (OPEN_DATE),
MONTH (OPEN_DATE)
) opened
FULL OUTER JOIN (
SELECT
YEAR (CLOSE_DATE) AS ano,
MONTH (CLOSE_DATE) AS mes,
COUNT (*) AS cnt
FROM
TABLE1,
TABLE2
WHERE
TABLE1.USERNAME = TABLE2.USERNAME
AND TABLE2.GROUP = 'SUPPORT'
GROUP BY
YEAR (CLOSE_DATE),
MONTH (CLOSE_DATE)
) closed ON opened.ano = closed.ano
AND opened.mes = closed.mes
ORDER BY
COALESCE (opened.ano, closed.ano) ASC,
COALESCE (opened.mes, closed.mes) ASC;
结果是:
情况:
由于select中没有空条件,因此第一行包含空值。
由于
答案 0 :(得分:1)
select
coalesce(opened.ano, closed.ano) as ano,
coalesce(opened.mes, closed.mes) as mes,
coalesce(opened.cnt, 0) as opened_cases,
coalesce(closed.cnt, 0) as closed_cases
from
(
select
year(open_time) as ano,
month(open_time) as mes,
count(*) as cnt
from table1
where groupdesc = 'SUPPORT'
group by year(open_time), month(open_time)
) opened
full outer join
(
select
year(close_time) as ano,
month(close_time) as mes,
count(*) as cnt
from table1
where groupdesc = 'SUPPORT'
group by year(close_time), month(close_time)
) closed
on opened.ano = closed.ano and opened.mes = closed.mes
where closed.mes is not null
order by coalesce(opened.ano, closed.ano) desc, coalesce(opened.mes, closed.mes) desc;
这是带有WHERE子句的SQL。 您的评论似乎表明您要查找的内容包含在此结果集中。 有10个Opened_cases和8个closed_cases。
答案 1 :(得分:1)
所以在你的小提琴示例中应该有10个打开的案例,8个已关闭?
是这样,然后试试这个:(http://sqlfiddle.com/#!3/3bf0ac/9)
;
with opened AS (
select
year(open_time) as ano,
month(open_time) as mes,
count(*) as cnt
from table1
where groupdesc = 'SUPPORT'
group by year(open_time), month(open_time)
),
closed AS (
select
year(close_time) as ano,
month(close_time) as mes,
count(*) as cnt
from table1
where groupdesc = 'SUPPORT'
group by year(close_time), month(close_time)
)
SELECT
COALESCE (opened.ano, closed.ano) AS ano,
COALESCE (opened.mes, closed.mes) AS mes,
COALESCE (opened.cnt, 0) AS opened_cases,
COALESCE (closed.cnt, 0) AS closed_cases
FROM opened
FULL OUTER JOIN closed on opened.ano = closed.ano and opened.mes = closed.mes
WHERE COALESCE (opened.ano, closed.ano) IS NOT NULL
ORDER BY coalesce(opened.ano, closed.ano) desc, coalesce(opened.mes, closed.mes) desc;