如标题所述,我想选择每个团队和每年的活动数量。下面的选择声明工作正常,但不能完全满足我的要求。
SELECT
Team.team_id,
TO_CHAR(Event.START_DATE_TIME, 'yyyy') AS year,
count(event_id) AS events
FROM
Team
LEFT OUTER JOIN
Event ON Event.team_id = Team.team_id
GROUP BY
TO_CHAR(Event.START_DATE_TIME, 'yyyy'),
team_id
ORDER BY
year ASC,
team_id ASC
;
有了这个,如果我们有:
Team 1 : 1 event in 2006
Team 2 : 1 event in 2007
我们获得:
ID | Year | Events
------------------
1 | 2006 | 1
2 | 2007 | 1
我想获得:
ID | Year | Events
-------------------
1 | 2006 | 1
2 | 2006 | 0
1 | 2007 | 0
2 | 2007 | 1
我不知道如何修改我的请求。
答案 0 :(得分:2)
使用:
SELECT x.team_id,
x.year,
COALESCE(COUNT(e.event_id), 0) AS events
FROM (SELECT :start_year + LEVEL - 1 AS year,
t.team_id
FROM DUAL, TEAM t
CONNECT BY :start_year + LEVEL - 1 <= :end_year) x
LEFT JOIN EVENT e ON EXTRACT(YEAR FROM e.start_date_time) = x.year
AND e.team_id = x.team_id
这将生成一个年份列表,但您必须设置:start_year
和:end_year
BIND变量。
此前:
SELECT x.team_id,
x.year,
COALESCE(COUNT(e.event_id), 0) AS events
FROM (SELECT 2006 AS year,
a.team_id
FROM TEAM a
UNION ALL
SELECT 2007,
b.team_id
FROM TEAM b) x
LEFT JOIN EVENT e ON EXTRACT(YEAR FROM e.start_date_time) = x.year
AND e.team_id = x.team_id
TO_CHAR可以获得年份,但是将其作为CHAR(4)返回,因此您需要使用TO_NUMBER(TO_CHAR(date_col, 'yyyy'))
来获取数字。所以我使用了EXTRACT代替......
答案 1 :(得分:1)
我这里没有Oracle进行测试,但总的来说这应该可行:
SELECT
Team.team_id,
Years.year,
COALESCE(count(Event.event_id),0) events
FROM
Team
JOIN (SELECT DISTINCT EXTRACT(YEAR FROM start_date_time) year FROM Event) Years ON 1=1
LEFT OUTER JOIN Event ON Event.team_id = Team.team_id AND EXTRACT(YEAR FROM Event.start_date_time) = Years.year
GROUP BY
Years.year,
team_id
ORDER BY
year ASC,
team_id ASC
;
您将获得每年的结果,您可以在活动中获得活动。如果这还不够,你可以用一个填满所有年份的表替换Years子。
答案 2 :(得分:1)
所以它有效! :) 这是我的最终查询:
SELECT
Team.name,
Years.year,
count(Event.event_id)
FROM
Team
JOIN
(
SELECT DISTINCT EXTRACT(YEAR FROM start_date_time) AS year
FROM Event
) Years ON 1 = 1
LEFT OUTER JOIN
Event ON Event.team_id = Team.team_id
AND EXTRACT(YEAR FROM Event.start_date_time) = Years.year
WHERE
event_type = 'C'
GROUP BY
Team.name,
Years.year
ORDER BY
Year ASC,
name ASC
;
谢谢!