我有一个优惠券表,其中包含字段 Id、CouponCode、CustomerUsageCount、CouponUsageCount 和其他一些必要字段。在 CustomerUsageCount 中,我存储客户可以使用优惠券的次数,例如如果 CustomerUsageCount = 1 那么每个客户都可以使用一次。在CouponUsageCount中,我存储了优惠券总共可以使用的次数,例如如果CouponUsageCount = 50,则优惠券只能使用50次,之后优惠券代码无效。
身份证 | 客户使用计数 | 优惠券使用次数 |
---|---|---|
1 | 1 | 50 |
2 | 2 | 100 |
我想在我的获取优惠券存储过程中应用这两个条件,以仅显示适用于特定客户的优惠券。为此,我加入了我的订单表,其中包含字段 Id、CustomerId、CouponId 以及其他字段
身份证 | 客户ID | 优惠券ID |
---|---|---|
11 | 15 | 2 |
12 | 8 | 1 |
这是我写的
SELECT DISTINCT
C.Id,
C.CouponCode,
C.CouponType,
C.DiscountType,
C.CouponValue,
C.MinimumSpend,
C.[Description],
C.PrintText
FROM tblCoupon C
LEFT JOIN tblOrder O ON O.CustomerId = @CustomerId
WHERE
(C.CustomerUsageCount is null OR
C.CustomerUsageCount > (SELECT COALESCE(COUNT(o.CouponId), 0) AS OrderCount
FROM tblOrder o
LEFT JOIN tblCoupon c ON o.CouponId = c.Id
WHERE o.CouponId = C.Id
AND o.CustomerId = @CustomerId)) AND
(C.CouponUsageCount is null OR
C.CouponUsageCount > (SELECT COALESCE(COUNT(o.CouponId), 0) AS OrderCount
FROM tblOrder o
LEFT JOIN tblCoupon c ON o.CouponId = c.Id
WHERE o.CouponId = C.Id)) AND
(C.StartDate <= CURRENT_TIMESTAMP AND CURRENT_TIMESTAMP <= C.EndDate) AND
C.CouponStatus = 1
我也尝试过
(C.CustomerUsageCount is null OR
C.CustomerUsageCount > (SELECT COUNT(CouponId)
FROM tblOrder
WHERE CouponId = C.Id AND
CustomerId = @CustomerId)) AND
(C.CouponUsageCount is null OR
C.CouponUsageCount > (SELECT COUNT(CouponId)
FROM tblOrder
WHERE CouponId = C.Id))
虽然这适用于未使用任何优惠券的客户,但不适用于至少使用过 1 张优惠券的客户。就像我有 5 张优惠券,而我的客户 15 使用了 couponId 4,我想显示所有其他优惠券给他4张优惠券,但不退还另外4张优惠券。
with CouponUsage as (
select CouponId,
count(*) as CouponUsedAll,
count(case when CustomerId = @CustomerId then 1 end) as CouponUsedCustomer
from Orders
group by CouponId
)
select *
from Coupons c inner join CouponUsage cu on cu.CouponId = c.Id
where <valid dates>