0

我有以下代码:

select O.ONO
from Customers C, Odetails Od, Orders O, Parts P
where P.PNO=Od.PNO and Od.ONO=O.ONO and O.CNO=C.CNO
group by O.ONO
order by sum(Od.QTY*P.PRICE)desc;

但是,O.ONO我需要C.CNAME从不同的表中选择列,而不是选择列。我该怎么做呢?

4

3 回答 3

1

如果您想要的是按订单总和排序的客户名称列表,那么只需将您的查询从

select O.ONO
...
group by O.ONO

select C.CName
...
group by C.CName

这将显示客户名称和订单号。注意:这将重复客户名称的次数与该客户的订单数量一样多

另外,我喜欢的 SQL 查询风格是

select C.CName
from Customers C
    INNER JOIN Orders O ON C.CNO = O.CNO
    INNER JOIN Odetails OD ON O.ONO = OD.ONO
    INNER JOIN Parts P ON OID.PNO = P.PNO
where P.PNO=Od.PNO and Od.ONO=O.ONO and O.CNO=C.CNO
group by C.CName
order by sum(Od.QTY*P.PRICE)desc;

澄清您的代码的附加建议。(请注意:我不是 oracle 人),在我的公司(SqlServer)中,通常您会拥有以实体命名的表,主键只是Id,然后是任何不带前缀的属性。例如 确实OIDOrderIdor OfficeId?

例如:

顾客:

  • ID
  • 姓名

命令:

  • ID
  • 客户ID

然后您的查询更具可读性:

SELECT Name
FROM Customer
    INNER JOIN Order ON Customer.Id = Order.CustomerId
WHERE ...
ORDER BY Customer.Name
于 2013-10-07T16:00:17.283 回答
0

请这样做,

select C.CNAME from Customers C, Odetails Od, Orders O, Parts P where P.PNO=Od.PNO and Od.ONO=O.ONO and O.CNO=C.CNO group by C.CNAME order by sum(Od.QTY*P.PRICE) desc;
于 2013-10-07T16:06:53.877 回答
0

select 语句将选择指定的列

SELECT C.CNAME
FROM Customers C, Odetails Od, Orders O, Parts P
WHERE P.PNO=Od.PNO and Od.ONO=O.ONO and O.CNO=C.CNO
GROUP BY C.CNAME
ORDER BY sum(Od.QTY*P.PRICE)desc;

如果您仍希望保持选中 O.ONO 列

SELECT C.CNAME, O.ONO
FROM Customers C, Odetails Od, Orders O, Parts P
WHERE P.PNO=Od.PNO and Od.ONO=O.ONO and O.CNO=C.CNO
GROUP BY C.CNAME
ORDER BY sum(Od.QTY*P.PRICE)desc;
于 2013-10-07T16:14:22.970 回答