我希望有人可能能夠指出我要去哪裏錯了,但我一直在尋找這最後30分鐘,並沒有得到任何地方它。選擇所有不在Top'n'中的數據爲'其他'
我有一個填充了數據的臨時表,前端應用程序不能爲我做任何邏輯,所以請原諒表中醜陋的case語句邏輯。
用戶對帶回的結果集感到滿意,因爲我得到前10條記錄。他們現在已經決定他們希望看到一組其他國家(所有排名不在前10位)作爲'其他'。
我試圖創建一個不在前10名的國家的分組,但它不工作,我正計劃將此結果聯合到前10名的結果中。
SELECT c.Country, count(*) AS 'Total_Number_of_customers', COALESCE(ili.new_customers,0) AS 'New_Customers', COALESCE(ilb.existing_first,0) AS 'Existing_First_Trans', COALESCE(ilc.existing_old,0) AS 'Existing_Prev_Trans'
FROM #customer_tmp c
LEFT JOIN (SELECT z.country, count(*) AS 'new_customers' FROM #customer_tmp z where z.customer_type='New_Customer' group by z.country)ili ON ili.country = c.country
LEFT JOIN (SELECT zy.country, count(*) AS 'existing_first' FROM #customer_tmp zy where zy.customer_type='Existing_Customer' AND zy.first_transaction=1 group by zy.country)ilb ON ilb.country = c.country
LEFT JOIN (SELECT zx.country, count(*) AS 'existing_old' FROM #customer_tmp zx where zx.customer_type='Existing_Customer' AND zx.first_transaction=0 group by zx.country)ilc ON ilc.country = c.country
GROUP BY c.country, ili.new_customers, ilb.existing_first, ilc.existing_old
ORDER BY 2 DESC
這是我用來從我的表中獲取結果的SQL。
作爲參考,我的臨時表中的每一行都包含一個客戶ID,它們的創建日期和客戶類型,具體針對我要實現的目標。
希望這是一個簡單的問題,我只是有點慢..
在進階非常感謝。
這裏有一個方法有一切都很好:-)非常感謝 – 2010-12-22 17:04:25