有人可以给我一个使用视图作为关系的查询示例吗?或者如何将此查询作为关系转换为视图?
SELECT COUNT(Y.custorderID) AS NoOfOrders, x.city ||' '||
EXTRACT(YEAR FROM TO_DATE(Y.dateorderplaced, 'DD-MON-RR'))
FROM (SELECT custorderid, custID, customerorder.dateorderplaced
FROM CustomerOrder
WHERE EXTRACT(MONTH FROM
TO_DATE(CustomerOrder.dateorderplaced, 'DD-MON-RR')) =1 AND EXTRACT(YEAR FROM
TO_DATE(CustomerOrder.dateorderplaced, 'DD-MON-RR')) = 2017
) Y
INNER JOIN Customer x
ON Y.custID = x.custID
GROUP BY x.city, y.dateOrderplaced
答案 0 :(得分:0)
Create view getProducts_v as (
SELECT *
FROM Product
WHERE Active = 'Y' and OnHandQty>0);
SELECT *
FROM GetProducts_v P
INNER JOIN ProductCategory PC
on PC.ProductID = P.ID
WHERE PC.Name in ('Houseware','Kitchen')
视图getProducts_v仅提供活动的项目列表以及存在的可用性。
然后,查询使用该视图获取家庭用品厨房中仅有这些产品的列表。由于视图已经过滤掉了非活动状态和那些具有0 onHandQty的视图,我们只向用户显示我们拥有的活动和活动状态。
拿走你拥有的东西:
CREATE view GetOrderHeader_v as (
SELECT custorderid, custID, customerorder.dateorderplaced
FROM CustomerOrder
);
SELECT COUNT(gOH.custorderID) AS NoOfOrders
, x.city ||' '|| EXTRACT(YEAR FROM TO_DATE(gOH.dateorderplaced, 'DD-MON-RR'))
FROM GetOrderHeader_v gOH
INNER JOIN Customer x
ON gOH.custID = x.custID
WHERE EXTRACT(MONTH FROM TO_DATE(gOH.dateorderplaced, 'DD-MON-RR')) =1
AND EXTRACT(YEAR FROM TO_DATE(gOH.dateorderplaced, 'DD-MON-RR')) = 2017
GROUP BY x.city ||' '|| EXTRACT(YEAR FROM TO_DATE(Y.dateorderplaced, 'DD-MON-RR'))
, gOH.dateOrderplaced;
注意如果字段已经是日期数据类型,我将不会使用上面的to_date,因为它会增加不必要的开销。如果dateorderplaced还没有日期,我会对表格结构有所顾虑。
通常我只会在复杂查询中使用这样的视图,或者我想在逻辑中包含一个表以消除冗余检查;比如我们只展示活跃的产品;但我们不会从产品表中删除产品,因此我们让开发人员参考GetProducts_v,它永远不会显示已删除的产品或缺货产品。