简体   繁体   English

从连接MySQL中其他表的两个不同的列中获取平均值

[英]get the average from two distinct columns joining other tables in MySQL

I have the following table in mySQL with sample data: 我在mySQL中有下表,其中包含示例数据:

Table1 : 表1

id    type    locid    month    qty
1     car1      1      JAN       2
2     car1      1      FEB       1
3     car1      2      JAN       3
4     car1      2      MAR       2
5     car2      1      FEB       2
6     car2      1      MAY       5

Table2 : 表2

id    location
1        CA
2        NY

I have difficulty in getting the average of the quantity from this distinct two columns which is the type and the location. 我很难从这两个不同的列(类型和位置)中获取数量的平均值。 Would it be possible to compute the average with in the past 3 months only? 仅在过去3个月内可以计算平均值吗?

Here is the result I would like to accomplish: 这是我想要完成的结果:

type      CA_AVE      NY_AVE
-----------------------------
car1        1.5         2.5
car2        2  <-- assumed the current month is MARCH so the qty for MAY should 
                   not be included to get the average

This is your answer. 这就是你的答案。 but you should conside now month is aug not march b/ci used now(). 但是您应该考虑一下,现在月份不是3月b / ci使用now()。 okey. 好。 so change your table data accordingly and check the result. 因此请相应地更改表格数据并检查结果。

select AVG( loc) as loc,AVG(qty) as qty from tbl1  where month NOT IN (concat(UCASE(DATE_FORMAT(date_add(now(), INTERVAL -1 MONTH),'%b')),',',
         UCASE(DATE_FORMAT(date_add(now(), INTERVAL -2 MONTH),'%b')),',',
         UCASE(DATE_FORMAT(date_add(now(), INTERVAL -3 MONTH),'%b')))) group by type

For DEMO Click here:- http://sqlfiddle.com/#!2/2a15e/15 对于DEMO,请单击此处:-http://sqlfiddle.com/#!2/ 2a15e/15

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM