我有两个表,都有列:tstamp, weight, destination我想写一个查询,从表a和表b中获取以下列到一个表中:Count() from a as Acounts, Count() from b as Bcounts, Sum(Acounts, Bcounts) where destination=xWhere datepart(hh,tstamp) =y。
我已经尝试了几个小时,使用联合、连接和子查询,但似乎找不到正确的解决方案。Bcounts列在我的表中没有显示为一列。相反,结果是作为单独的一行出现在Acounts下。
我不是一个SQL的家伙,因为我主要是用PLC工作。我明天会把我的代码贴出来。
这是一个PostgreSQL的例子。
create table a (tstamp timestamp, weight int, destination text);
create table b (tstamp timestamp, weight int, destination text);
insert into a values
('2020-01-01 10:00:00', 40, 'germany'), ('2019-01-01 10:00:00', 50, 'germany'),
('2020-04-01 10:00:00', 10, 'germany'), ('2019-04-01 10:00:00', 20, 'germany'),
('2020-01-01 11:00:00', 40, 'congo'), ('2019-01-01 11:00:00', 50, 'congo'),
('2020-04-01 11:00:00', 10, 'congo'), ('2019-04-01 12:00:00', 20, 'congo');
insert into b values
('2020-01-01 10:00:00', 40, 'germany'), ('2019-01-01 10:00:00', 50, 'germany'),
('2020-04-01 11:00:00', 10, 'congo'), ('2019-04-01 11:00:00', 20, 'congo');
我们从表A中获取计数并放入一个关于来源的标记,然后将其与表b中的同类信息相结合。case
语句,以选择性地分别拉出a和b的计数,也可以结合使用。
with combined as (
select count(*) as counter, 'a' as source from a
where destination = 'germany' and date_part('hour', tstamp) = 10
union all
select count(*) as counter, 'b' as source from b
where destination = 'germany' and date_part('hour', tstamp) = 10
)
select
sum(case when source = 'a' then counter else 0 end) as count_a,
sum(case when source = 'b' then counter else 0 end) as count_b,
sum(counter) as counter_a_b
from combined
count_a /dbfiddle.uk?rdbms=postgres_12&fiddle=100b4d5d4c94789d2f2c05d79c464166。
相当于SQL Server例子。
with combined as (
select count(*) as counter, 'a' as source from a
where destination = 'germany' and datepart(hh, tstamp) = 10
union all
select count(*) as counter, 'b' as source from b
where destination = 'germany' and datepart(hh, tstamp) = 10
)
select
sum(case when source = 'a' then counter else 0 end) as count_a,
sum(case when source = 'b' then counter else 0 end) as count_b,
sum(counter) as counter_a_b
from combined
相当于MySQL例子。
select
sum(case when source = 'a' then counter else 0 end) as count_a,
sum(case when source = 'b' then counter else 0 end) as count_b,
sum(counter) as counter_a_b
from (
select count(*) as counter, 'a' as source from a
where destination = 'germany' and hour(tstamp) = 10
union all
select count(*) as counter, 'b' as source from b
where destination = 'germany' and hour(tstamp) = 10
) t