我正在为我的网站创建一份报告,我将列出不同的房产价格 locations.I有一个如下表
CREATE TABLE report(report_id INT NOT NULL PRIMARY KEY AUTO_INCREMENT NOT NULL, Locations VARCHAR(255), date VARCHAR(255), ratepersqft INT);
我在表格中的值如下
INSERT INTO report(Locations, date, ratepersqft)
VALUES('Location A', '2012-01-16', 2500),
('Location B', '2012-01-21', 1750),
('Location C', '2012-01-20', 1650),
('Location C', '2012-02-19', 2100),
('Location A', '2012-02-18', 2560),
('Location B', '2012-02-12', 1790),
('Location C', '2012-03-04', 2250),
('Location A', '2012-03-25', 2680),
('Location B', '2012-03-05', 2540),
('Location A', '2012-08-21', 2870),
('Location C', '2012-09-12', 2150),
('Location B', '2012-10-18', 2760);
位置|月| RatePerSqFt
Location A Jan 2500
Location A Feb 2560
Location A March 2680
Location A August 2870
Location A sept 2870
Location A oct 2870
Location B Jan 1750
Location B Feb 1790
Location B March 2540
Location B August 2540
Location B sept 2540
Location B oct 2760
Location C Jan 1650
Location C Feb 2100
Location C March 2250
Location C August 2250
Location C sept 2250
Location C oct 2760
我想为表中可用的所有可能数据绘制值。如果您看到表格位置A没有10月份的任何条目。但由于位置B有10月份的条目,我想在输出表格中输入一个条目,其中包含位置A的最后一个月8月的登记率。
所以它显示为2870。
同样地,位置B没有8月的条目。但是由于位置A具有8月份的费率,我将带来位置B并填充上个月的2540年费率。
C相同。
如何为上述
编写查询或proc答案 0 :(得分:0)
看起来像分组是你正在寻找的
SELECT Locations, date_format(date,'%b') as month, sum(ratepersqft) as rates
FROM report GROUP BY Locations, month(date);
我不确定sum
。可能应该是avg
或其他。
答案 1 :(得分:0)
select Locations,year,month,
(select ratepersqft from report where
Locations=tl.locations
and
DATE_FORMAT(date,'%Y%m')<=tp.monthNum
order by DATE_FORMAT(date,'%Y%m') desc
limit 1) as t
from
(select distinct Locations from report) tl,
(select distinct YEAR(date) year,
MONTHName(date) month,
DATE_FORMAT(date,'%Y%m') monthNum
from report) tp
order by Locations,monthNum