我需要一些帮助来解决查询问题。我想加入两个select语句的输出:
第一
select extract(year from createdDate) as year,
count(extract(year from createdDate)) as count
from table
where to_user_id= 322
group by extract(year from createdDate);
及其输出
Year Count
2014 18
2015 117
2016 9
和第二次查询
select count(extract(year from createdDate)) as count
from table
where userId=322
group by extract(year from createdDate);
及其输出
Count
18
110
11
我想将这两个表添加到一个表中。 我想要那种类型的输出,
Year Count Count
2014 18 18
2015 117 110
2016 9 11
请注意,我在查询1中使用to_user_id
,但在查询2中使用userId
。
我试图解决这个问题,但我在输出中得到了重复的值。 有人知道解决方案吗?
答案 0 :(得分:3)
将它们写为子查询并将它们连接在一起。
SELECT a.year, a.count AS t_user_count, b.count AS user_count
FROM (select YEAR(create_date) AS year, COUNT(*) AS count
FROM table
WHERE to_user_id = 322
GROUP BY year) AS a
JOIN (SELECT YEAR(create_date) AS year, COUNT(*) AS count
FROM table
WHERE user_id = 322
GROUP BY year) AS b
ON a.year = b.year