0

我有 3 张桌子

sales
-----------
date 
order_id

product_details 
-----------
product_id
cost
price

order_detail 
-----------
product_id
order_id

我必须减去日期在__和__之间的成本和价格的总和以显示盈亏

我已经尝试过了,但没有显示出什么结果

SELECT ( SUM(p.price) - SUM(p.cost) )
FROM   product_details AS p
       LEFT JOIN order_detail AS o
         ON o.product_id = p.product_id
       JOIN sales AS s
         ON s.order_id = o.order_id
WHERE  s.[date] = ' 15.08.2013' 
4

3 回答 3

1

假设 product_id 和 order_id 是唯一的:

SELECT SUM(p.price) - SUM(p.cost) AS Profit
FROM sales s
INNER JOIN order_detail AS o ON s.order_id = o.order_id
INNER JOIN product_details AS p ON o.product_id = p.product_id
WHERE s.Date BETWEEN '15.08.2013' AND '16.08.2013'
于 2013-08-22T20:16:27.240 回答
1

听起来你需要GROUP BY在你的条款中,因为你正在寻找每个的总利润product id

SELECT SUM(pd.price) - SUM(pd.cost)
FROM product_details pd
    LEFT JOIN order_details od ON pd.product_id = od.product_id
    INNER JOIN sales s ON od.order_id = s.order_id
-- This is where you'd change your date filter
WHERE s.Date BETWEEN '20.07.2013' AND '20.08.2013'
GROUP BY pd.product_id
于 2013-08-22T20:23:24.940 回答
1

您的查询是正确的。只需确认您使用的日期范围即可。或者尝试在查询中获取日期,然后在 where 子句中相应地使用它。

SELECT s.[date],( SUM(p.price) - SUM(p.cost) )
FROM   product_details AS p
LEFT JOIN order_detail AS o
ON o.product_id = p.product_id
JOIN sales AS s
ON s.order_id = o.order_id
group by s.[date]

由于订单 ID 不是唯一的,请尝试以下操作:

with order_cte(product_id,order_id)as 
(select distinct Product_id, Order_Id from order_detail)

SELECT s.[date],( SUM(p.price) - SUM(p.cost) )
FROM   product_details AS p
LEFT JOIN order_cte AS o
ON o.product_id = p.product_id
JOIN sales AS s
ON s.order_id = o.order_id
group by s.[date]
于 2013-08-22T20:23:52.020 回答