我已经编写了一个类似于
的h2 db的查询SELECT o.order_id, o.order_date , o.petrol_qty, (o.price) as price_per_litre , (o.price * petrol_qty) as total_Price, t.truck_code
FROM ORDERZ o left join truck t ON o.truck_id = t.truck_id
group by o.order_id
结果如此这是一个orderz表
ORDER_ID ORDER_DATE PETROL_QTY PRICE_PER_LITRE TOTAL_PRICE TRUCK_CODE
1 2005-01-01 12.0 5.8 69.6 BY2354
2 2006-01-21 13.0 2.8 36.4 BY2994
3 2006-01-21 13.0 2.8 36.4 BY8754
4 2006-01-21 13.0 2.8 36.4 BY8754
5 2006-01-21 13.0 2.8 36.4 BY2354
在卡车表中我希望每辆卡车每月获得平均汽油量(汽油应该是订单表中的汽油数量) 我被卡住了,因为我不确切地知道如何为每辆卡车做一个月平均值,请帮忙。
这些是我的表
CREATE TABLE truck (
truck_id INT NOT NULL AUTO_INCREMENT,
truck_code VARCHAR(255) NOT NULL,
purchased_date VARCHAR(255) NOT NULL,
description VARCHAR(255) NOT NULL,
PRIMARY KEY (truck_id)
);
DROP TABLE IF EXISTS order;
CREATE TABLE IF NOT EXISTS orderz (
order_id INT NOT NULL AUTO_INCREMENT,
petrol_qty DOUBLE NOT NULL,
price DOUBLE NOT NULL DEFAULT 0,
order_date Date NOT NULL,
truck_id INT,
PRIMARY KEY (order_id),
FOREIGN KEY (truck_id) REFERENCES truck(truck_id)
ON UPDATE CASCADE
ON DELETE CASCADE
);
NOte- truck_code是唯一的 我想要卡车表看起来像 truck_id truck_code avg_amount_petrol_qty_per_month,我只使用h2 db
答案 0 :(得分:3)
H2 DB文档具有以下功能:MONTH(date)
,YEAR(date)
和聚合函数AVG()
。可以使用MONTHNAME(日期)而不是MONTH(日期)。
试试这个?
A)按卡车代码分组,年份和月份:
select t.truck_code, year(order_date) as year, month(order_date) as month,
avg(petrol_qty) as avg_petrol_qty from
truck t inner join orderz o
on t.truck_id = o.truck_id
group by t.truck_code, year(order_date), month(order_date)
order by t.truck_code, year(order_date), month(order_date)
B)按卡车代码和月份分组:
select t.truck_code, month(order_date) as month,
avg(petrol_qty) as avg_petrol_qty from
truck t inner join orderz o
on t.truck_id = o.truck_id
group by t.truck_code, month(order_date)
order by t.truck_code, month(order_date)