0

这是我的 sql 小提琴http://sqlfiddle.com/#!2/9e6691/3

[第一季: 01] [第二季: 04] [第三季: 07] [第四季: 10]

我正在研究一个谷歌图表,我正在为单独的项目创建图表。图表由两条线组成。一行将提到该项目的 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 作为公共位置。我需要计算这些项目相对于上述日期的平均值。

例如。price_id: 1,5,9 每平方英尺的价格是 2800,0,2500 第一季度的平均值是 1766。同样我需要为每个季度计算。

4

3 回答 3

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;  
于 2013-01-31T13:05:28.817 回答
1

?

被接受的答案不只是一种令人费解的说法:

SELECT QUARTER(date) dt
     , common_location
     , ROUND(avg(rate_per_sqft)) as RatePerSqFt 
  FROM ratepersqft
 GROUP 
    BY dt
     , common_location  ;

?

于 2013-01-31T12:56:34.373 回答
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

SQL 小提琴:http ://sqlfiddle.com/#!2/9e6691/23

于 2013-01-31T12:57:36.663 回答