我有2张桌子
tbl_vacancies_details
tbl_filled_vacancies
我想要显示一个图表,其中包含每年空缺和填充计数的总数。如何为此编写SQL查询。
tbl_vacancies_details
Id | Year | Count |
------------------------
1 | Jan-2014 | 10 |
2 | Jun-2014 | 5 |
3 | Dec-2015 | 9 |
tbl_filled_details
Id | Join_Date | UserId |
------------------------
1 | Mar-2014 | 1 |
2 | Dec-2014 | 6 |
2 | Dec-2014 | 15 |
3 | May-2016 | 3 |
我想要的输出是
Year | Total | Filled |
-----------------------
2014 | 15 | 3 |
2015 | 3 | 0 |
2016 | 0 | 3 |
答案 0 :(得分:1)
答案 1 :(得分:0)
SELECT
(CASE
WHEN vac.year not null then to_char(vac.Year,'YYYY')
ELSE to_char(det.Year,'YYYY')) as Year,
sum(vac.Count) as Total,
det.Count as Filled
FROM
tbl_vacancies_details vac FULL
OUTER JOIN (
SELECT
to_char(fil.Join_Date,'YYYY') as Year,
count(*) as Count
FROM
tbl_filled_details as fil
GROUP BY
to_char(fil.Join_Date,'YYYY')
) det ON det.Year = vac.Year
GROUP BY
to_char(vac.Year,'YYYY')
我认为这展示了如何做到这一点的想法,但我不确定它是否是runnalbe查询。您必须根据格式找到转换日期的功能。
完全超越tbl_vacancies_details每年加入内部选择(计算每年tbl_filled_details中vac的出现次数),然后显示每年的两个结果
编辑:我认为tbl_filled_details有假期的个案记录,tbl_vacancies_details已经有假期总和
答案 2 :(得分:0)
我建议使用聚合union all
查询:
select yyyy,
sum(total) as total,
sum(filled) as filled
from ((select year(year) as yyyy, count as total, 0 as filled
from tbl_vacancies_details
) union all
(select year(join_date) as yyyy, 0 as total, 1 as filled
from tbl_filled_details
)
) x
group by yyyy;
Here是一个SQL小提琴。
注意:我建议您不要将列命名为count
和year
,因为它们在SQL中用于其他目的。