如何从引用另一个表的两列中聚合数据,并获得过去3个月的每月总数?

pxy2qtax  于 2021-06-24  发布在  Mysql
关注(0)|答案(1)|浏览(247)

使用以下数据:
我如何根据事件中的两列(犯罪\包含,相似\包含)得到每个事件的成本总和 listofincidents table?
另外,我如何获得过去3个月(1月、2月和3月)的金额?

create table crimeincidents (
  id int not null,
  name varchar(20),
  primary key (id)
);

create table listofincidents (
  id int not null,
  incidentdate datetime 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, incidentdate, crime_incidentid,
  similar_incidentid, cost_to_city) 
 values
  (1, "2018-01-10 18:48:00", 1, 2, 900),
  (2, "2018-02-15 14:48:00", 2, 3, 800),
  (3, "2018-02-20 18:10:00", 3, 1, 1500.10), 
  (4, "2018-03-20 18:48:00", 1, 3, 800.23),
  (5, "2018-03-25 18:24:00", 1, 3, 200.00),
  (6, "2018-04-15 10:12:00", 1, 2, 400.00);

生成不带每月日期的结果的查询是:

select c.id, c.name, 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;

我想使用过去3个月的数据生成成本。最终结果如下:

1. January   | 1500.1   |   1900.23
2. February  | 900      |   800
3. March     | 1800.23  |   1500.1
hwazgwia

hwazgwia1#

我想这就是你想要的:

SELECT DATE_FORMAT(li.incidentdate, '%Y-%m') as date,
ci.name,
SUM(
li.cost_to_city
) as totalCost
FROM crimeincidents ci
JOIN listofincidents li ON ci.id = li.crime_incidentid OR ci.id = li.similar_incidentid
GROUP BY date, ci.id
ORDER BY date

你可以选择:

SELECT CONCAT(YEAR(li.incidentdate), ' ', MONTHNAME(li.incidentdate)) as month,
ci.name,
SUM(
li.cost_to_city
) as totalCost
FROM crimeincidents ci
JOIN listofincidents li ON ci.id = li.crime_incidentid OR ci.id = li.similar_incidentid
GROUP BY month, ci.id
ORDER BY month

以更好地满足您的要求。
一开始没注意到你想把“事件”和“类似事件”分开。虽然我觉得很奇怪(因为类似的事件本身也可能有类似的事件),但我还是做了一个问题:

SELECT CONCAT(YEAR(li.incidentdate), ' ', MONTHNAME(li.incidentdate)) as month,
ci.name,
SUM(
IF(ci.id = li.id, li.cost_to_city,0)
) as totalCostIncident,
SUM(
IF(ci.id = li.similar_incidentid, li.cost_to_city,0)
) as totalCostSimilarIncident
FROM crimeincidents ci
JOIN listofincidents li ON ci.id = li.crime_incidentid OR ci.id = li.similar_incidentid
GROUP BY month, ci.id
ORDER BY month

相关问题