我在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