同义词,外连接,单行字符串函数

时间:2015-07-23 17:15:50

标签: mysql oracle

如何在订单明细表中返回订单ID和每个订单的总数量总和。将总价值标记为" Total qtys"并且只返回总数量> gt的订单250并根据总数量从最高到最低对此进行排序?

1 个答案:

答案 0 :(得分:0)

这是为了mysql。假设你指的是sum(qty)

架构/加载数据测试

create table orders
(   id int auto_increment primary key,
    custId int not null 
    -- etc etc
    -- fk to customer id
);

create table orderDetails
(   
    id int auto_increment primary key,
    orderId int not null,
    itemId int not null,
    qty int not null,
    -- etc etc
    -- fk to items table not shown in the example

    -- fk constraint to orders table below: 
    CONSTRAINT fk_orddet_ords FOREIGN KEY (orderId) REFERENCES orders(id)
);

insert orders (custId) values (1),(2),(3);
insert orderDetails (orderId,itemId,qty) values (1,1,9),(2,1,190),(2,1,100),(3,1,255);

-- the below shows that the fk constraint fails for faulty data (orderId 4 does not exist)
insert orderDetails (orderId,itemId,qty) values (4,1,9);

查询

如果您没有执行 inr ,那么ID 2将无法显示(即如果您只是在qty> 250处进行加入)。并不是说那里没有聪明的头脑,但这里是我的:

select id,custId,qty from 
(select o.id,o.custId,sum(d.qty) as qty
from orders o
join orderDetails d
on d.orderId=o.id
group by o.id,o.custId) inr
where inr.qty>250
order by qty desc

+----+--------+------+
| id | custId | qty  |
+----+--------+------+
|  2 |      2 |  290 |
|  3 |      3 |  255 |
+----+--------+------+
2 rows in set (0.05 sec)