我正在做作业,被困在某些东西上,希望有人能提供帮助。
我有两个桌子。我需要对pp_Orders中的pp_inventory_id进行计数,然后提取关联的名称,地址等。来自第二个表nc_Customer。最终结果应该是产生购买了三件或以上商品的顾客的姓名和地址。
我可以使每个查询单独工作,但应该创建一个查询。我怀疑UNION是要走的路,但我只是想不通如何将两者作为一个查询一起使用。任何建议将不胜感激。
第一个查询选择,计数并产生正确的ID#:
(
SELECT pp_inventory_id, COUNT(*) AS "Number of Orders"
FROM pp_Order
GROUP BY pp_inventory_id
HAVING COUNT(pp_Order.pp_inventory_id) >=3
)
第二个查询选择购买了所述商品ID的客户的正确客户信息:
SELECT
nc_first_name,
nc_last_name,
nc_street_address,
nc_state_plus_zipcode,
pp_Order.pp_inventory_id
FROM nc_Customer
JOIN pp_Order on pp_Order.pp_customer_id = nc_customer_id
GROUP BY nc_first_name, nc_last_name, nc_street_address,
nc_state_plus_zipcode, pp_Order.pp_inventory_id
答案 0 :(得分:2)
如果我正确理解了您的问题,那么您需要与该查询相关联的相应客户信息,该信息已经为您服务(3个或更多的订单)?如果是这样,您可以在exists
子句中移动该查询:
select *
from nc_customer c
where exists (
select 1
from pp_order o
where o.pp_customer_id = c.nc_customer_id
group by o.pp_inventory_id
having count(o.pp_inventory_id) >= 3
)
答案 1 :(得分:0)
您可以使用它们之间的联接合并查询
select T1.*,T2.* from
(
SELECT pp_inventory_id, COUNT(*) AS "Number of Orders"
FROM pp_Order
GROUP BY pp_inventory_id
HAVING COUNT(pp_Order.pp_inventory_id) >=3
) as T1
inner join
(SELECT
nc_first_name,
nc_last_name,
nc_street_address,
nc_state_plus_zipcode,
pp_Order.pp_inventory_id
FROM nc_Customer
JOIN pp_Order on pp_Order.pp_customer_id = nc_customer_id
GROUP BY nc_first_name, nc_last_name, nc_street_address, nc_state_plus_zipcode, pp_Order.pp_inventory_id
) as T2 on T1.pp_inventory_id=T2.pp_inventory_id