我有两张桌子,Tickets和Discount。我必须数一数折扣ID组合可应用于Ticket表中订单的次数:
Tickets表:
ITEMID | CATEGORYID
-------+-----------
1 | 11
1 | 11
1 | 11
2 | 11
3 | 12
4 | 13
4 | 13
5 | 14Discounts表:
DiscountID | ITEMID | CATEGORYID
-----------+--------+-----------
1 | 1 | 11
1 | 4 | 13
2 | 1 | 11
2 | 6 | 15
3 | 1 | 11
3 | 5 | 14结果: DiscountID 1可应用于Ticket表两次,DiscountID 3可应用一次。
我目前设法通过循环在存储过程,它是缓慢的,因为我必须循环每个折扣项目与所有门票项目手动。
我想知道是否有更好的方法通过JOIN和INTERSECT结合使用SQL。我无法理解这件事,我必须同时在折扣表中匹配1排以上。
更好的解释:
没有任何折扣的原始表格:Tickets表:
ITEMID | CATEGORYID
-------+-----------
1 | 11
1 | 11
1 | 11
2 | 11
3 | 12
4 | 13
4 | 13
5 | 14应用折扣ID 1:
DiscountID | ITEMID | CATEGORYID
-----------+--------+-----------
1 | 1 | 11
1 | 4 | 13折扣ID 1计算了两次,因为:
ITEMID | CATEGORYID
-------+-----------
1 | 11
1 | 11
4 | 13
4 | 13现在进入折扣ID 2:
DiscountID | ITEMID | CATEGORYID
-----------+--------+-----------
2 | 1 | 11
2 | 6 | 15删除计数的DiscountID 1项:
ITEMID | CATEGORYID
-------+-----------
1 | 11
2 | 11
3 | 12
5 | 14折扣ID 2的计数为0,因为在票务表1\ 11中只能匹配一条双头ID 2的记录。
而
6\ 15在票表中不可用。由于折扣ID 2不匹配,票证表中没有删除任何内容
现在转到折扣ID 3:
DiscountID / ITEMID \x\x{e76f}\{e76f}\x{e76f}
3 | 5 | 14
ITEMID | CATEGORYID
-------+-----------
1 | 11
2 | 11
3 | 12
5 | 14一次计算折扣ID 3,现在删除计数记录
ITEMID | CATEGORYID
-------+-----------
2 | 11
3 | 12由于我不知道如何通过SQL执行上面的操作,所以我不知道如何输出:
DISCOUNTID | APPLIED
-----------+-----------
1 | 2
3 | 1发布于 2018-07-10 09:14:05
这就行了。
select distinct d.*
from discounts d
inner join tickets t on t.itemId = d.itemid
and t.categoryId = d.categoryId它会给你
DiscountID | ITEMID | CATEGORYID
-----------+--------+-----------
1 | 1 | 11
1 | 4 | 13
2 | 1 | 11
3 | 5 | 14然后,您可以根据需要对所有列进行汇总。
select discountid, count(*) as apply_discount_x_times from ( select distinct d.discountid, d.itemId, d.categoryId from discounts d inner join tickets t on t.itemId = d.itemid and t.categoryId = d.categoryId ) x group by discountid
给你
DiscountID | apply_discount_x_times -----------+-------- 1 | 2 2 | 1 3 | 2
发布于 2018-07-10 09:25:31
select distinct d.*, CA.cnt
from discounts d
CROSS APPLY
(SELECT count(0) cnt from tickets t2
join discounts d2
on d.DiscountId = d2.discountid
and d2.itemid = t2.itemid
and d2.categoryid = t2.categoryid) CAhttps://stackoverflow.com/questions/51260804
复制相似问题