我有两个没有任何关系的不同表,但是我需要对两者的行数求和,并使用日期进行分组。我需要这种方式,因为我需要在元数据库中绘制图表。
我需要用它来总结用户每天观看的视频广告的数量,不幸的是,这是划分的。
我尝试了此SQL并几乎成功了:
select *, total_video_prize + total_video_stock
from (select last_video_watched, count(*) as total_video_prize from video_ads_user_historic group by DAY(last_video_watched)) as video_prize,
(select date_when_transacted, count(*) as total_video_stock from stock_historic where has_seen_video_ad = true group by DAY(date_when_transacted)) as video_stock
问题在于日期未合并。我需要last_video_watched与date_when_transacted相同,并按天分组。可以这样做吗?
答案 0 :(得分:1)
您可以使用UNION获取日期,然后与子查询一起进行计数
select t1.my_day , t2.total_video_prize , t3.total_video_stock
from (
select DAY(date_when_transacted) as my_day
from stock_historic
union
select DAY(last_video_watched)
from video_ads_user_historic
) t1
left join (
select DAY(last_video_watched) my_day, count(*) as total_video_prize
from video_ads_user_historic
group by DAY(last_video_watched)
) t2 on t2.myday = t1.my_day
left join (
selectDAY(date_when_transacted) my_day, count(*) as total_video_stock
from stock_historic
where has_seen_video_ad = true
group by DAY(date_when_transacted)
) t3 on t3.my_day = t1.my_day
答案 1 :(得分:1)
无论两个表中的哪个表,每个记录都代表观看的电影。因此,将表的行与UNION ALL
粘合在一起并计数:
select dt, count(*)
from
(
select last_video_watched as dt from video_ads_user_historic
union all
select date_when_transacted as dt from stock_historic where has_seen_video_ad = true
) unioned
group by dt
order by dt;
如果您的日期列包含时间部分,请使用DATE(column)
而不是仅列。
答案 2 :(得分:1)
我认为最简单的解决方案就是a <- matrix(rep(1:2, 30), 2, 30)
a <- paste0("p", 1:30, ":")
和union all
:
group by
不需要加入。