从第二个查询SQL添加列

时间:2014-11-13 12:53:13

标签: sql oracle join union

我试图将两个查询的结果连接到同一个结果表中,我不知道如何做到这一点。我试图使用UNION和JOIN操作符,但无法弄明白。这是我要连接的两个查询的SQL。两个单独的查询都会得到他们应该得到的结果。提前谢谢!

SELECT s.Store_Num || ': ' || s.Store_Name AS "Store",
        COUNT(e.Store_Num) AS "Total Rented"
FROM Employee e JOIN store s ON e.Store_Num = s.Store_Num
        JOIN rental r ON e.Emp_ID = r.Emp_ID
        JOIN rented_item ri ON r.Rental_Num = ri.Rental_Num
WHERE(SYSDATE - Rent_Date) < 60
GROUP BY s.Store_Num, s.Store_Name;
UNION
SELECT COUNT(i.Store_Num) AS "Total Inventory"
FROM inventory i JOIN store s ON i.Store_Num = s.Store_Num
GROUP BY s.Store_Num, s.Store_Name;

3 个答案:

答案 0 :(得分:4)

只需将多个Sub-Selects打包成一个语句!

你有两个计数行的查询,所以它们应该写成两个查询,每个查询都有一个COUNT(*),因为你计算行数,或者你应该使用COUNT(item_num),因为你计算的是项目,而不是商店,这个对读者来说会更清楚。

然后,您只需选择所有商店,并为每个商店在子查询中执行两项计数 - 这很容易维护,优化程序应该获得正确的连接谓词。

SELECT s.Store_Num || ': ' || s.Store_Name "Store",
       ( SELECT COUNT(*)
           FROM Employee e
           JOIN rental r ON e.Emp_ID = r.Emp_ID
           JOIN rented_item ri ON r.Rental_Num = ri.Rental_Num
          WHERE e.Store_Num = s.Store_Num
            AND (SYSDATE - Rent_Date) < 60
       ) "Total Rented",
       ( SELECT COUNT(*)
           FROM inventory i WHERE i.Store_Num = s.Store_Num
       ) "Total Inventory"
  FROM store s
;

答案 1 :(得分:2)

从你的专栏来看,UNION不是你想要的。一些不同的选项是使用JOIN或子查询。我不知道您的所有数据是如何设置的,但这应该很接近。

SELECT s.Store_Num || ': ' || s.Store_Name AS "Store",
        COUNT(e.Store_Num) AS "Total Rented", (
          SELECT COUNT(i.Store_Num) 
          FROM inventory i 
          WHERE i.Store_Num = s.Store_Num) AS "Total Inventory"
FROM Employee e 
JOIN store s 
ON e.Store_Num = s.Store_Num
JOIN rental r ON e.Emp_ID = r.Emp_ID
JOIN rented_item ri ON r.Rental_Num = ri.Rental_Num
WHERE(SYSDATE - Rent_Date) < 60
GROUP BY s.Store_Num, s.Store_Name;

答案 2 :(得分:0)

尝试此查询: -

SELECT s.Store_Num || ': ' || s.Store_Name AS "Store", COUNT(e.Store_Num) AS "Total Rented",
       COUNT(i.Store_Num) AS "Total Inventory"
FROM Employee e JOIN store s ON e.Store_Num = s.Store_Num
JOIN rental r ON e.Emp_ID = r.Emp_ID
JOIN rented_item ri ON r.Rental_Num = ri.Rental_Num
JOIN inventory i ON i.Store_Num = s.Store_Num
WHERE(SYSDATE - Rent_Date) < 60
GROUP BY s.Store_Num, s.Store_Name;

这可能会对你有帮助。