count_b

问题描述 投票:0回答:1

我有两个表,都有列: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工作。我明天会把我的代码贴出来。

sql union addition multiple-tables
1个回答
0
投票

这是一个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例子。

https:/dbfiddle.uk?rdbms=sqlserver_2017&fiddle=ff9dd4f864792437cb27d143106db186。

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例子。

https:/dbfiddle.uk?rdbms=mysql_5.5&fiddle=660b0c84c0c1b04141d19cc8c6b6af6d。

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

© www.soinside.com 2019 - 2024. All rights reserved.