显示订购确切图书的客户的custID> 1

时间:2014-04-10 09:08:36

标签: sql-server-2008 tsql

目标是找到订购同一本书的客户> 1在订单上。例如:

order_id |order_line |book_id | quantity | order_price
--------- ----------- -------- --------- -----------
33034      1           1619      10         $35
33034      2           1619       5         $16

这是对的吗?

SELECT distinct cust_id
    ,(SELECT cust_name_last
      FROM bkorders.customers AS CS
      WHERE CS.cust_id = OH.cust_id) AS cust_name_last
FROM bkorders.order_headers AS OH
WHERE EXISTS
    (SELECT 1
     FROM bkorders.order_details AS OD
     WHERE order_id > 1
     AND OD.order_id = OH.order_id
     HAVING COUNT(distinct order_line) > 1)

我附上了我正在使用的三个表的屏幕截图。 enter image description here

编辑:我们只使用子查询来完成此任务

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT distinct cust_id
    ,(SELECT cust_name_last
      FROM bkorders.customers AS CS
      WHERE CS.cust_id = OH.cust_id) AS cust_name_last
FROM bkorders.order_headers AS OH
WHERE EXISTS
    (SELECT 1 FROM bkorders.order_details OD
    WHERE OD.order_id = OH.order_id
    GROUP BY order_id, book_id HAVING count(*)>1)