加入三个表sql

时间:2013-08-22 19:59:46

标签: sql sql-server

我有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' 

3 个答案:

答案 0 :(得分: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'

答案 1 :(得分: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

答案 2 :(得分: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]