我有一个表,其中包含以下列
CampName -- Camp Name
CampId -- Camp Code
CouponCode -- Coupon Code
IsClaimed -- Boolean flag saying if a coupon is claim or not . True or False
此表包含所有优惠券。如果Isclaimed标志设置为true,则使用优惠券。此col的默认值为False
现在我需要创建另一个表
VoucherRegister:
CampaignName
CampaignCode
VoucherUsed --> Number of voucher of a specfic campaign which are used
VoucherUnUsed --> Number of voucher of a specfic campaign which are unused
关于如何创建它的任何想法
答案 0 :(得分:0)
由于您的IsClaimed列为布尔值,您可以将1和按CampName和CampId分组
select CampName CampaignName
,CampId CampaignCode
, sum(IsClaimed) VoucherUsed
, sum(NOT IsClaimed) VoucherUnUsed
from my_table
group by CampName, CampId
答案 1 :(得分:0)
这将起作用:
select cmpname,campid,
(select sum(couponcode) from tablename group by campname where Isclaimed='IsTrue' )
VoucherUsed,
(select sum(couponcode) from tablename group by campname where Isclaimed='IsFalse' )
VoucherUnused
from tablename group by campname,Campid;
答案 2 :(得分:0)
通用方法将使用条件聚合:
select CampName as CampaignName,
CampId CampaignCode,
sum(case when IsClaimed then 1 else 0 end) as VoucherUsed
sum(case when IsClaimed then 0 else 1 end) as VoucherUnUsed
from my_table
group by CampName, CampId;
根据您所使用的数据库,可能有更简单的表达方式,但是以上内容可以在任何数据库中使用。
答案 3 :(得分:0)
我的方法
Select
T1.CampId AS Campaign_No
,T1.CampName AS Campaign_Name
,(Select Count(T11.CampId) From LocalVouchers T11 where T11.IsClaimed = 'True' and T11.CampId=T1.CampId ) AS Voucher_Used
,(Select Count(T12.CampId) From LocalVouchers T12 where T12.IsClaimed = 'False' and T12.CampId=T1.CampId) AS Voucher_Unused
来自 本地优惠券T1 通过...分组 T1.CampId ,T1.CampName
是上述解决方案的组合