1

我已经尝试了几个小时来自学并学习如何使用我的虚拟测试数据列出所有客户以及他们每个人下的订单。我想返回 CustomerID、CustomerName、OrderTypeName 和计数“OrderCount”

我尝试了一些在网上找到的不同方法和技术,但我一直遇到类似/不同的问题,这些问题都与我无法弄清楚的明显简单的解决方案有关。

这是我当前的查询。

SELECT 
    c.CustomerID, c.CustomerName, t.OrderTypeName
FROM 
    tblCustomer c, tblOrder o, tblOrderType t
INNER JOIN
    (SELECT 
         o.CustomerID, COUNT(o.CustomerID) AS OrderCount
     FROM
         tblOrder o, tblCustomer c
     WHERE 
         o.CustomerID = c.CustomerID)
ORDER BY CustomerName;

这个目前在关键字“ORDER”附近给出了不正确的语法错误。

4

3 回答 3

1

You're mixing old-style joins with comma-separated lists of tables and the proper ANSI standard INNER JOIN - but you're not providing any join condition.

My suggestion: get used to the ANSI standard and use it - all the time!

SELECT 
    c.CustomerID, c.CustomerName, t.OrderTypeName
FROM 
    tblCustomer c
INNER JOIN 
    tblOrder o ON ..(what links tblOrder and tblCustomer??) ....
INNER JOIN
    tblOrderType t ON ....(what links OrderType and Order??) ....
INNER JOIN
    (SELECT 
         o.CustomerID, COUNT(o.CustomerID) AS OrderCount
     FROM
         tblOrder o
     INNER JOIN
         tblCustomer c ON .....(missing join condition again).....
     WHERE 
         o.CustomerID = c.CustomerID) x ON .....(again: missing join condition here).....
ORDER BY CustomerName;
于 2013-05-15T13:10:34.813 回答
0

Making an assumption in terms of how the ordertype table connects to the orders table:

SELECT 
c.CustomerID
,c.CustomerName
,t.OrderTypeName
,COUNT(o.customer_id) as num_orders
FROM tblCustomer c
INNER JOIN tblOrder o on o.customer_id = c.customer_id
INNER JOIN tblOrderType t ON t.order_id = o.order_id
GROUP BY
c.CustomerID
,c.CustomerName
,t.OrderTypeName
ORDER BY 
c.customer_id
于 2013-05-15T13:09:55.727 回答
0

当您执行 aJOIN时,您需要指定要加入这两个表的字段:

例如:

select t1.a,t2.b from table1 t1 join table2 t2 on t1.id= t2.id

所以我猜你没有阅读你说的正确的指南。

要解决您的问题,您需要选择要使用的语法类型。逗号分隔的(非常旧的)或提供的join condition(推荐的)。

于 2013-05-15T13:13:37.683 回答