缺少右括号问题

时间:2014-02-06 19:51:45

标签: sql

这是我写的查询

Select C.CUST_NAME,P.PROD_DESCRIP  from Customer C
JOIN (Ord O,OrderItem OT, Product P) ON (C.CUST_ID = O.CUST_ID AND O.ORD_ID = OT.ORD_ID AND OT.PROD_ID = P.PROD_ID) GROUP BY  C.CUST_NAME ORDER BY OT.ORDITEM_QTY DESC

但问题是它给了我右括号缺少问题

3 个答案:

答案 0 :(得分:5)

虽然在某些数据库中允许使用连接语法,但拆分连接更加清晰:

Select C.CUST_NAME, P.PROD_DESCRIP 
from Customer C JOIN 
     Ord O
     on C.CUST_ID = O.CUST_ID JOIN
     OrderItem OT
     on O.ORD_ID = OT.ORD_ID JOIN
     Product P
     ON OT.PROD_ID = P.PROD_ID
GROUP BY C.CUST_NAME
ORDER BY OT.ORDITEM_QTY DESC;

顺便说一句,这可能不是你认为它做的。它返回一个客户名称以及一个任意prod_descrip。然后按任意数量对此结果进行排序 - 可能来自相同或不同的行。

如果您想获得客户名称以及该客户的最大数量的产品,您可以这样做:

Select C.CUST_NAME,
       substring_index(group_concat(P.PROD_DESCRIP  order by OT.ORDITEM_QTY desc), ',', 1) as PROD_DESCRIP
from Customer C JOIN 
     Ord O
     on C.CUST_ID = O.CUST_ID JOIN
     OrderItem OT
     on O.ORD_ID = OT.ORD_ID JOIN
     Product P
     ON OT.PROD_ID = P.PROD_ID
GROUP BY C.CUST_NAME;

注意:如果PROD_DESCRIP可以使用逗号,那么您将需要使用其他分隔符。

编辑:

以上是MySQL解决方案。在Oracle中,您可以这样做:

select CUST_NAME, PROD_DESCRIP
from (Select C.CUST_NAME, P.PROD_DESCRIP,
             row_number() over (partition by C.CUST_NAME order by OT.ORDITEM_QTY desc) as seqnum
      from Customer C JOIN 
           Ord O
           on C.CUST_ID = O.CUST_ID JOIN
           OrderItem OT
           on O.ORD_ID = OT.ORD_ID JOIN
           Product P
           ON OT.PROD_ID = P.PROD_ID
     ) t
where seqnum = 1;

这实际上是首选的标准SQL解决方案。它适用于大多数数据库(SQL Server,Oracle,Postgres,DB2和Teradata)。

答案 1 :(得分:1)

SELECT C.CUST_NAME, P.PROD_DESCRIP 
FROM Customer C
  INNER JOIN Ord O ON C.CUST_ID = O.CUST_ID
  INNER JOIN OrderItem OT ON O.ORD_ID = OT.ORD_ID
  INNER JOIN Product P ON OT.PROD_ID = P.PROD_ID
GROUP BY C.CUST_NAME 
ORDER BY OT.ORDITEM_QTY DESC

答案 2 :(得分:0)

SELECT C.CUST_NAME,P.PROD_DESCRIP  
FROM Customer C
JOIN Ord O
  ON C.CUST_ID = O.CUST_ID
JOIN OrderItem OT
  ON O.ORD_ID = OT.ORD_ID 
JOIN Product P
  ON OT.PROD_ID = P.PROD_ID
GROUP BY C.CUST_NAME 
ORDER BY OT.ORDITEM_QTY DESC