我想計算產品顯示在兩個日期之間的事件。我必須填寫9欄,每欄都有其他產品類型。過濾聲明而不使用從
我想問你是否有可能將這個聲明縮短。 下面的SQL是第一次工作,但不是有效的嘗試。
with events(event_id, customer_id) as (
select * from event
where start_date >= :stare_date
and end_date <= :end_date
),
select
(select count(*) from event_product where event_id in (select event_id from events where customer_id = customer.customer_id) and product_type = 'YLW') customer_ylw_products -- it works but its ugly and non effective
-------
-- repeat seven times for other type of products
-------
(select count(*) from event_product where event_id in (select event_id from events where customer_id = customer.customer_id) and product_type = 'RTL') customer_rtl_products
from customer
;
注意,排隊
(select event_id from events where customer_id = customer.customer_id)
重複約9倍。
我一直在試圖短以下這一個附加:
with events(event_id, customer_id) as (
select * from event
where start_date >= :stare_date
and end_date <= :end_date
),
**customer_events (event_id, customer_id) as (select * from events)**
select
(select count(*) from event_product where event_id in (select event_id from customer_events) and product_type = 'RTL') customer_rtl_products
from customers
where customer_events.customer_id = customer.customer_id -- doesnt works
having customer_events.customer_id = customer.customer_id -- doesnt works
什麼是您的DBMS? – Dimt 2014-08-27 13:00:56
與mssqlserver,你可以用transact-sql參數化存儲過程或函數編寫。我想其他dbms有類似的功能。 – user2504380 2014-08-27 13:05:31
@Dimt:這是Oracle – ImportError 2014-08-27 13:06:10