我在vfp中使用SQL,所以我的一些命令是不同的。使用iif([condition],[if true],[if false])
代替case when
。
这是我的代码:
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 / etc.),但如果它是另一个字段,它应该计算两次捐赠者。
示例:捐赠者#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
答案 0 :(得分:1)
我认为你可以逃脱COUNT(不同的捐赠者)AS total_gifts,我没有视觉狐狸专业人士,并做了一些谷歌搜索,并提到它。
答案 1 :(得分:1)
如何使用在所有相关字段上分组的单个查询(看起来像giftource,语言,续订和类型),以便为每个组合获取一条记录,并显示所需的计数:
SELECT giftsource, language, renew, type, COUNT(*) ;
FROM <whatever tables and joins you need> ;
GROUP BY giftsource, language, renew, type
然后,您可以将此连接到您需要的任何其他内容,或使用一些Xbase代码将其拉入单行。您还可以查看交叉表(使用VFPXTab或第三方工具之一)来转移数据。