![](/img/trans.png)
[英]MySQL: get distinct values from two columns and check whether they occur in two other columns of the same table
[英]get the average from two distinct columns joining other tables in MySQL
我在mySQL中有下表,其中包含示例數據:
表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
表2 :
id location
1 CA
2 NY
我很難從這兩個不同的列(類型和位置)中獲取數量的平均值。 僅在過去3個月內可以計算平均值嗎?
這是我想要完成的結果:
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
這就是你的答案。 但是您應該考慮一下,現在月份不是3月b / ci使用now()。 好。 因此請相應地更改表格數據並檢查結果。
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
對於DEMO,請單擊此處:-http://sqlfiddle.com/#!2/ 2a15e/15
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.