这是我的sql fiddle http://sqlfiddle.com/#!2/9e6691/3
[Quater 1:01] [Quater 2:04] [Quater 3:07] [Quater 4:10]
我正在开发Google图表,我正在为单独的项目创建图表。图表由两行组成。一行将提到该项目的ratepersquarefeet。其他线路希望得到关于四分之一和公共位置的平均值。
编码如下:
CREATE TABLE IF NOT EXISTS `ratepersqft` (
`price_id` int(11) NOT NULL auto_increment,
`project_id` int(11) default NULL,
`date` varchar(255) default NULL,
`rate_per_sqft` double default NULL,
`common_location` varchar(255) default NULL,
PRIMARY KEY (`price_id`));
INSERT INTO `ratepersqft` (`price_id`, `project_id`, `date`, `rate_per_sqft`, `common_location`) VALUES
(1, 26, '2012-01-17 ', 2800, 'ECR'),
(2, 54, '2012-04-17 ', 1550, 'ECR'),
(3, 53, '2012-07-17 ', 1850, 'ECR'),
(4, 58, '2012-10-17 ', 4425, 'ECR'),
(5, 85, '2012-01-17 ', 0, 'ECR'),
(6, 114, '2012-04-17 ', 2650, 'ECR'),
(7, 131, '2012-07-17 ', 2400, 'ECR'),
(8, 134, '2012-10-17 ', 2900, 'ECR'),
(9, 140, '2012-01-17 ', 2500, 'ECR'),
(10, 368, '2012-04-17 ', 1650, 'ECR'),
(11, 369, '2012-07-17 ', 1800, 'ECR'),
(12, 370, '2012-10-17 ', 2000, 'ECR'),
(13, 26, '2012-04-17 ', 2800, 'ECR'),
(14, 26, '2012-07-17 ', 2800, 'ECR'),
(15, 26, '2012-10-17 ', 2800, 'ECR');
例如。在小提琴中,我将项目ID 26作为其在ECR中的共同位置
图表中的第一行将与该项目中的ratepersquarefeet有关。还有一些其他项目将ECR作为共同位置。我需要计算这些项目相对于上述日期的平均值。
对于Eg。 price_id:1,5,9每平方英尺的费率是2800,0,2500 First Quater的平均值是1766.就像我需要为每个季度计算一样。
答案 0 :(得分:2)
SELECT ROUND(avg(rate_per_sqft)) as RatePerSqFt
FROM ratepersqft
WHERE common_location = 'ECR' AND
1 <= MONTH(date) AND MONTH(date) <3
group by common_location
UNION
SELECT ROUND(avg(rate_per_sqft)) as RatePerSqFt
FROM ratepersqft
WHERE common_location = 'ECR' AND
3 <= MONTH(date) AND MONTH(date)<6
group by common_location
UNION
SELECT ROUND(avg(rate_per_sqft)) as RatePerSqFt
FROM ratepersqft
WHERE common_location = 'ECR' AND
6 <= MONTH(date) AND MONTH(date)<9
group by common_location
UNION
SELECT ROUND(avg(rate_per_sqft)) as RatePerSqFt
FROM ratepersqft
WHERE common_location = 'ECR' AND
9 <= MONTH(date) AND MONTH(date)<=12
group by common_location;
答案 1 :(得分:1)
接受的答案不是一种令人费解的说法:
SELECT QUARTER(date) dt
, common_location
, ROUND(avg(rate_per_sqft)) as RatePerSqFt
FROM ratepersqft
GROUP
BY dt
, common_location ;
答案 2 :(得分:1)
您可以通过在子选择中按季度/位置计算平均值然后再次加入表格来实现此目的。
这是我提出的查询:
select *
from ratepersqft r
join (
SELECT
quarter(`date`) as quarter,
year(`date`) as year,
avg(rate_per_sqft) as QuarterAverage,
common_location
FROM ratepersqft
group by
quarter(`date`),
year(`date`),
common_location
) averages
on year(r.`date`) = averages.year
and quarter(r.`date`) = averages.quarter
and r.common_location = averages.common_location
WHERE project_id = 26