[英]SQL Subquery returns multiple rows when grouping by
我有兩個表,都有列:tstamp、weight、destination 我正在嘗試編寫一個查詢以將表 a 和 b 中的以下列放入一個表中:a 中的 Count( ) 作為 Acounts, b 中的 Count() 作為 Bcounts , Sum(Acounts, Bcounts) where destination=x where datepart(hh,tstamp) =y
我已經嘗試了幾個小時使用聯合、連接和子查詢,但似乎找不到正確的解決方案。 Bcounts 列未作為列顯示在我的表中。 相反,結果顯示為帳戶下的單獨行。
我不是 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 | 計數_b | counter_a_b ------: | ------: | ----------: 4 | 2 | 6
示例: https://dbfiddle.uk/?rdbms=postgres_12&fiddle=100b4d5d4c94789d2f2c05d79c464166
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
示例: https://dbfiddle.uk/?rdbms=sqlserver_2017&fiddle=ff9dd4f864792437cb27d143106db186
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
示例: https://dbfiddle.uk/?rdbms=mysql_5.5&fiddle=660b0c84c0c1b04141d19cc8c6b6af6d
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.