我在vfp中使用SQL,所以我的一些命令是不同的。使用iif([condition],[if true],[if false])
代替case when
。當字段唯一時選擇count()
這裏是我的代碼:
SELECT
giftsource,
COUNT(donor) AS total_gifts, /*this is not the one that need fixed*/
SUM(amt) AS total_amt,
SUM(iif(unique = 1 AND language != 'F' AND renew = '0' AND type = 'IN',1,0)) as d_Count_E_New_Indiv,
SUM(iif(unique = 1 AND language = 'F' AND renew = '0' AND type = 'IN',1,0)) as d_Count_F_New_Indiv,
SUM(iif(unique = 1 AND language != 'F' AND renew != '0' AND type = 'IN',1,0)) as d_Count_E_Re_Indiv,
SUM(iif(unique = 1 AND language = 'F' AND renew != '0' AND type = 'IN',1,0)) as d_Count_F_Re_Indiv,
SUM(iif(unique = 1 AND language != 'F' AND renew = '0' AND type != 'IN',1,0)) as d_Count_E_New_Org,
SUM(iif(unique = 1 AND language = 'F' AND renew = '0' AND type != 'IN',1,0)) as d_Count_F_New_Org,
SUM(iif(unique = 1 AND language != 'F' AND renew != '0' AND type != 'IN',1,0)) as d_Count_E_Re_Org,
SUM(iif(unique = 1 AND language = 'F' AND renew != '0' AND type != 'IN',1,0)) as d_Count_F_Re_Org,
FROM (select *,
cast(/* equivalent to a bunch of if elses*/
iif( list_code="WEB","1",
iif( list_code="GRO","2",
iif( list_code="CHO","3",
iif( list_code="TEL","4",
iif( list_code="TES","5",
iif( list_code="POS" AND amt < 10000,"6",
iif((LIKE(list_code,"4%") OR list_code = "4") AND amt < 10000,"7",
iif((LIKE(list_code,"4%") OR list_code = "4" OR list_code = "POS") AND amt >= 10000,"8",
iif( LIKE(list_code,"9%") OR list_code = "9","9",
"10"))))))))) as c(1))
as giftsource
from cGift) gift
LEFT JOIN
(select didnumb, language, type from dp) d
on cast(gift.donor as i) = cast(d.didnumb as i)
LEFT JOIN /*this does not do what i want it to*/
(select min(gidnumb) gid, 1 as unique from cGift group by donor) uGift
on gift.gidnumb = uGift.gid
GROUP BY giftsource
ORDER BY giftsource
這段代碼應該做的是找到每個禮品類內捐了許多捐助者。它不應該統計同一領域內的重複捐贈者(即相同的list_code/lang/renew /等),但如果是另一個領域,它應該計數捐獻者兩次。
示例:捐獻者#3只能在d_Count_E_New_Indiv中計數一次,但也可以在d_Count_E_New_Org中計數。
gidnumb是此表中的主鍵。
隨着我的第二次加入,我給表中的第一個捐助者附加了一個字段(名爲unique)。這是行不通的,因爲它只計算一個領域的捐助者。
有人能告訴我什麼是正確的做法嗎?我還有更多的SUM(...)不是基於獨特的捐助者,所以我寧願不要屠殺我的選擇太多。
編輯:我固定它通過以下select count(distinct IIF(renew = '0' AND lang != 'F',donor,0)) FROM dpgift
謝謝,我已經實現了與此非常相似的內容。 – slicedtoad 2012-02-28 15:25:00