在mysql中获取不同时间段的特定数据

时间:2019-03-19 06:00:14

标签: mysql

我有一张这样的桌子

--------------------------------
|name    | time | city |value  | 
--------------------------------
|a       | 2018| rasht | 1.5   |
--------------------------------
|a       | 2017| rasht | 2     |
--------------------------------
|a       | 2018| tehran| 4     |
--------------------------------
|a       | 2017| rasht | 3     |
--------------------------------
|a       | 2018| rasht | 5     |
--------------------------------
|a       | 2017| rasht | 2     |
--------------------------------
|b       | 2018| tehran| 7     |
--------------------------------

我喜欢这样从表中获取数据:

name | city | total 2018 | total 2017
a    |rasht | 6.5        |7
a    |theran| 4          |0
b    |theran| 7          |0

我正在使用这样的查询:

select A.name,city,A.sum(value) ,B.sum(value) from
(select * from tbl where year=2018 group by name,city)A,
(select * from tbl where year=2017 group by name,city)B
where A.name=B.name and A.city=B.city

但是它不起作用,对于像b这样在2017年没有价值的记录,它什么也不返回

如您所见,我的示例非常简单,如果您可以在此地址Fiddle中看到它,则我将准确地设置为db。

我也使用此代码:

 select subzone, mvFeederName, SUM(CASE WHEN faultStartDate >= 13970901 and faultEndDate <= 13971101 and (subzone=10 ) THEN energyLost ELSE 0 END) AS `unplannedCurrentEnergyLost`, SUM(CASE WHEN faultStartDate >= 13960901 and faultEndDate <= 13961101 and (subzone=10 ) THEN energyLost ELSE 0 END) AS `unplannedLastYearEnergyLost`, count(CASE WHEN faultStartDate >= 13970901 and faultEndDate <= 13971101 and (subzone=10 ) THEN mvFeederName ELSE 0 END) AS `unplannedCurrentCount`, count(CASE WHEN faultStartDate >= 13960901 and faultEndDate <= 13961101 and (subzone=10 ) THEN mvFeederName ELSE 0 END) AS `unplannedLastYearCount` from faults_mv group by subzone,mvFeederName 

在两个时间段内,energyLost求和列的返回值为零,在两个时间段内,mvFeederName的计数相同,这是不正确的。

2 个答案:

答案 0 :(得分:2)

使用条件聚合-

select name, city, 
       sum(case when time=2018 then value end) 'total 2018',
       sum(case when time=2017 then value end) 'total 2017'
from tablename
group by name, city

答案 1 :(得分:2)

您可以使用条件聚合来获得所需的结果:

SELECT name, city,
    SUM(CASE WHEN time = 2018 THEN value ELSE 0 END) AS `total 2018`,
    SUM(CASE WHEN time = 2017 THEN value ELSE 0 END) AS `total 2017`
FROM tbl
GROUP BY name, city

输出:

name    city    total 2018  total 2017
a       rasht   6.5         7
a       tehran  4           0
b       tehran  7           0

Demo on dbfiddle