3

对于下面的架构,我需要获取此报告

这就是我所拥有的

select c.name, sr.name, count(o.order_id)
from contact c 
INNER JOIN accounts a
ON c.account_id=a.account_id
INNER JOIN sales_reps sr 
ON a.sales_rep_id =sr.sales_rep_id
INNER JOIN orders o
ON a.account_id =o.account_id
where o.order_id in (
    select SUM(oi.quantity*p.price) from 
    order_items oi INNER JOIN parts p
    on oi.part_id =p.part_id
)
group by a.account_id, c.name

但这并没有给出任何结果。

请帮忙。

4

3 回答 3

3

它不会给出结果,因为您的 WHERE ... IN SELECT 基于返回 sum() 值的查询,该值不等于键(很可能),或者充其量是不正确的...并且因为您正在处理数量和价格将具有小数精度(通常),你甚至不会得到匹配,甚至不太可能......

我会交换查询以对给定日期内的订单进行资格预审,然后总结...然后加入休息...

select
         c.name, 
         sr.name,
         PreQualified.NumberOrders,
         PreQualified.OrderTotal
      from
         ( select 
                 o.Account_ID,
                 count( distinct o.order_id ) as NumberOrders,
                 sum( oi.quantity * p.price ) as OrderTotal
              from 
                 orders o
                    join order_items oi
                       on o.order_id = oi.order_id
                       join parts p
                          on oi.part_id = p.part_id
              where
                 o.Delivery_Date >= CURDATE()
              group by
                 o.Account_ID ) as PreQualified
            JOIN Accounts a
               on PreQualified.Account_ID = a.Account_ID
               Join Contact C
                  on a.Account_ID = c.Account_ID
            JOIN Sales_Reps sr
               ON a.sales_rep_id = sr.sales_rep_id 
于 2012-08-24T02:52:28.117 回答
3

你的 where 条件不对,order_id 怎么应该等于 sum?

试试下面的:

select 
    c.name, sr.name, COUNT(o.order_id), SUM(op.order_total)
FROM 
    contact c 
INNER JOIN 
    accounts a ON c.account_id = a.account_id
INNER JOIN 
    sales_reps sr ON a.sales_rep_id = sr.sales_rep_id
INNER JOIN 
    orders o ON a.account_id = o.account_id
INNER JOIN 
  (SELECT 
      oi.order_id, SUM(oi.quantity * p.price) AS order_total
  FROM 
      order_items oi 
  INNER JOIN 
      parts p ON oi.part_id = p.part_id 
  GROUP BY 
      oi.order_id
  ) op ON o.order_id = op.order_id
WHERE o.delivery_data >= CURDATE()
GROUP by c.contact_id
于 2012-08-24T03:00:27.520 回答
0

如果要计算记录,请使用

count(*)

代替

count(o.order_id)
于 2012-08-24T02:48:58.740 回答