![](/img/trans.png)
[英]How do i aggregate data from 2 columns referencing another table and also get the monthly totals for the past 3 months?
[英]How do i aggregate data from 2 columns referencing another table?
使用以下數據,我如何基於事件列表中的2列(crime_incidentid,相似_事件ID)獲取每個事件的成本總和。
create table crimeincidents
(
id int not null,
name varchar(20),
primary key (id)
);
create table listofincidents
(
id int not null,
crime_incidentid int not null,
similar_incidentid int not null,
cost_to_city decimal(8,2),
primary key (id),
FOREIGN KEY (crime_incidentid) REFERENCES crimeincidents(id),
FOREIGN KEY (similar_incidentid) REFERENCES crimeincidents(id)
);
insert into crimeincidents (id,name) values (1,'Burglary'),(2,'Theft'), (3, 'Grand theft auto');
insert into listofincidents (id, crime_incidentid, similar_incidentid, cost_to_city)
values (1, 1, 2, 900), (2, 2, 3, 800), (3, 3, 1, 1500.10), (4, 1, 3, 800.23);
I want to get an aggregate data similar to the table below.
---------------------------------------------------------------
id name | similarIncidentCost | crimeIncidentCost
1 Burglary | 1500.10 | 1700.23
2 Theft | 900 | 800
3 Grand Theft Auto | 1600.23 | 1500.1
為了最安全起見,您需要使用單獨的結果集進行similarIncidentCost
, crimeIncidentCost
結果集包含similarIncidentCost
和crimeIncidentCost
select c.id, sm.similarIncidentCost, cr.crimeIncidentCost from crimeincidents c
inner join (
select c.id, sum(s.cost_to_city) similarIncidentCost
from crimeincidents c inner join listofincidents s
on s.similar_incidentid = c.id
group by c.id
) sm on sm.id = c.id
inner join (
select c.id, sum(cr.cost_to_city) crimeIncidentCost
from crimeincidents c inner join listofincidents cr
on cr.crime_incidentid = c.id
group by c.id
) cr on cr.id = c.id
同樣,您也可以通過union all
探索union all
select id, sum(case when type = 'sim' then cost_to_city else 0 end) similarIncidentCost,
sum(case when type = 'cr' then cost_to_city else 0 end) crimeIncidentCost
from
(
select c.id, s.cost_to_city, 'sim' as type
from crimeincidents c left join listofincidents s
on s.similar_incidentid = c.id
union all
select c.id, cr.cost_to_city, 'cr' as type
from crimeincidents c left join listofincidents cr
on cr.crime_incidentid = c.id
)t
group by id
您可以使用以下內容
with report as(
select c.id,c.name,sum(cost_to_city) as total,Type='crimeIncidentCost'
from crimeincidents c
inner join listofincidents l on l.crime_incidentid = c.id
group by c.id,c.name
union all
select c.id,c.name,sum(cost_to_city) as total,Type='similarIncidentCost'
from crimeincidents c
inner join listofincidents l on l.similar_incidentid = c.id
group by c.id,c.name)
select id,name, [similarIncidentCost],[crimeIncidentCost]
from report r
pivot( sum(total) for Type in([similarIncidentCost],[crimeIncidentCost])) p
這是一個工作演示
結果
id name crime_incidentid similar_incidentid
1 Burglary 1700.23 1500.1
3 Grand theft auto 1500.1 1600.23
2 Theft 800 900
希望這個能對您有所幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.