SQL>合并两个select语句

时间:2013-11-30 02:28:10

标签: sql oracle

1

SELECT v.NAME,
  CASE 
    WHEN va.state_territory_province = 'Illinois'
      THEN 'Illinois'
    END Vendors
FROM grocery.vendor v
INNER JOIN grocery.vendor_address va ON va.vendor_id = v.vendor_id
WHERE va.state_territory_province = 'Illinois';

2

SELECT vendor_id,
  CASE 
    WHEN count(DISTINCT product_id) > 2
      THEN 'High'
    END
FROM grocery.can_supply
HAVING count(DISTINCT product_id) > 2
GROUP BY vendor_id
ORDER BY vendor_id;

我必须尝试回答的问题是: 所有可以提供多个项目或位于伊利诺伊州的供应商的全名是什么?

我知道如何单独编写它们,但我需要将它们一起编写,这让我很困惑。

EDITED

我试过UNION,它给了我这个错误:

  

*   第1行的错误:   ORA-00923:未找到FROM关键字

SQL> SELECT vc.contact_name,
       CASE
         WHEN va.state_territory_province = 'Illinois'
           THEN 'Availible' 
       END CheckAvail
     FROM grocery.vendor_address va 
     INNER JOIN grocery.vendor_contact vc ON vc.vendor_id = va.vendor_id 
     WHERE va.state_territory_province = 'Illinois' union select vc.contact_name
         CASE
            WHEN count(distinct cs.product_id) > 1 
              THEN 'Avail' 
         END CheckAvail from grocery.vendor cs;

3 个答案:

答案 0 :(得分:0)

如果您有两个返回相同字段但具有不同选择逻辑的查询,则使用UNION运算符组合其结果,例如

select c1, c2 from ... where ...
union
select c1, c2 from ... where ...

答案 1 :(得分:0)

我可能会使用这样的sub-select

SELECT v.NAME,
CASE 
WHEN va.state_territory_province = 'Illinois'
  THEN 'Illinois'
END Vendors
FROM grocery.vendor v
INNER JOIN grocery.vendor_address va ON va.vendor_id = v.vendor_id
WHERE va.state_territory_province = 'Illinois' AND v.vendor_id IN (
  SELECT vendor_id FROM grocery.can_supply
  HAVING count(DISTINCT product_id) > 2
  GROUP BY vendor_id
  ORDER BY vendor_id);

答案 2 :(得分:0)

这里有很多选择。你可以做左连接(见下文)存在语句,工会。 CTP样式预先选择。

SELECT v.NAME
      , ISNULL(va.state_territory_province, '')  Vendors
      , ISNULL(inv.Desc, '') AS Desc 
FROM grocery.vendor v
LEFT JOIN grocery.vendor_address va ON va.vendor_id = v.vendor_id AND  va.state_territory_province = 'Illinois' 
LEFT JOIN (SELECT vendor_id,
             CASE WHEN count(DISTINCT product_id) > 2 THEN 'High' END AS desc
           FROM grocery.can_supply
           HAVING count(DISTINCT product_id) > 2
            GROUP BY vendor_id) inv ON inv.Vendor_Id = v.Vendor_Id 
WHERE 1=1
     AND (va.Vendor_Id NOT IS NULL OR inv.Vendor_ID NOT IS NULL)