【发布时间】:2018-08-14 16:57:52
【问题描述】:
我有这样的表
Customer
-ID
-name
-address
Business
-ID
-name
-type
Discount
-ID
-amount
-BusinessID
-position
UsedDiscounts
-CustomerID
-DiscountID
企业有很多折扣。
用户使用过很多折扣,记录在 UsedDiscounts 中。
用户只能按顺序使用折扣,由位置定义。折扣 1,然后是折扣 2。因此,即使企业有 10 个折扣,客户有资格获得的一个是该企业使用折扣的位置 + 1。
目标:获得用户有资格享受的所有折扣。
我的方法是对折扣和二手折扣进行左排除联接。
因此,获得所有折扣减去使用过的折扣,然后以某种方式最小化位置并获得所有“合格”的折扣。但是,我可能可以在 SQL 中实现这一点,但我不知道如何......
示例不完整的 SQL 如下所示
SELECT *, min(gd.position) FROM
(SELECT * FROM "Deals" as d WHERE (d.active = true) AND (d.latitude BETWEEN 40 AND 41) AND (d.longitude BETWEEN -75 AND -70)) AS gd
LEFT JOIN
(SELECT du."DealId" FROM "DealsUsed" AS du WHERE du."CustomerId" = 1) AS bd
ON gd.id = bd."DealId"
WHERE bd."DealId" IS NULL
GROUP BY gd."UserId";
输出错误
Sample data:
Customer
--------
id name address
0 Tobby 93903903
1 Emi 3839039
2 Loop 393030
Business
--------
id name type
0 Cool flower
1 Corner car
2 New deli
3 Side printing
4 Big car
Discount
--------
id amount businessId position
0 10 0 0
1 22 3 1
2 10 3 2
3 43 2 0
4 23 5 0
5 10 5 1
Used Discount
----------
customerId discountId
1 2
outcome for customer 1 , emi, shouuld be
Discounts
--------
id amount businessId position
0 10 0 0
4 23 5 0
3 43 2 0
5 10 5 1
【问题讨论】:
-
显示示例数据和预期结果。
-
客户与企业的关系在哪里?是 discount.position = customer.id 吗?
-
是的,客户关系只是为了打折
-
但好点也许可以取消关系
-
你确定要使用这个
WHERE bd."DealId" IS NULL吗?在您的示例数据中看不到它。
标签: sql node.js postgresql sequelize.js