2013-07-04 105 views
-1

我有超過400萬行的龐大的數據庫,看起來像一個收集:SQL子查詢,從3行

Customer ID Shop 
1   Asda 
1   Sainsbury 
1   Tesco 
2   TEsco 
2   Tesco 

我需要計算的客戶,過去4個星期內,在所有3個店樂購塞恩斯伯裏已經逛過和阿斯達。你可以請建議,如果它可能與子查詢做到這一點?

+1

你的桌子裏有日期欄嗎?必須嘗試寫入查詢以返回結果嗎?請張貼您的表格結構以及您爲獲得所需結果所做的任何嘗試。 – Taryn

回答

0

這是「set-set-sets」子查詢的一個示例。你可以用聚合來解決它:

select customer_id 
from Yourtable t 
where <shopping date within last four weeks> 
group by customer_id 
having sum(case when shop = 'Asda' then 1 else 0 end) > 0 and 
     sum(case when shop = 'Sainsbury' then 1 else 0 end) > 0 and 
     sum(case when shop = 'Tesco' then 1 else 0 end) > 0; 

這個結構非常靈活。所以,如果你想阿斯達和特易購,但不塞恩斯伯裏,那麼你會怎麼做:

select customer_id 
from Yourtable t 
where <shopping date within last four weeks> 
group by customer_id 
having sum(case when shop = 'Asda' then 1 else 0 end) > 0 and 
     sum(case when shop = 'Sainsbury' then 1 else 0 end) = 0 and 
     sum(case when shop = 'Tesco' then 1 else 0 end) > 0; 

編輯:

如果你想有一個數,然後用這個作爲一個子查詢和統計結果:

select count(*) 
from (select customer_id 
     from Yourtable t 
     where <shopping date within last four weeks> 
     group by customer_id 
     having sum(case when shop = 'Asda' then 1 else 0 end) > 0 and 
      sum(case when shop = 'Sainsbury' then 1 else 0 end) > 0 and 
      sum(case when shop = 'Tesco' then 1 else 0 end) > 0 
    ) t 
+0

非常感謝你。我仍然是新來的SQL如此抱歉,如果這個問題聽起來很愚蠢,但我可以說在查詢的開始選擇計數(customer_id)如果只想音量不是所有的customer_ids?感謝 – user2551606

+0

SELECT COUNT(*) 從(從dm3_owner.EARN_FACT選擇a.ACCOUNT_NUMBER 左連接pad_owner.ssl_stores C於a.location_code = c.locn_code 其中 '20130626' 之間a.tran_date_id和 '20130701' 組由a.ACCOUNT_NUMBER 具有總和(當c.STORE_FORMAT ='便利店'然後1否則0結束時的情況]> 0和 總和(case.C.STORE_FORMAT ='PETROL STATIONS'then 1 else 0 end)> 0和 sum (case c.STORE_FORMAT ='SUPERSTORES'then 1 else 0 end)> 0 )dm3_owner.EARN_FACT a但它不起作用 – user2551606