我有这两个表:两个表的SQL总和
我需要加入付款表与折扣表。由于折扣表没有付款日期,预计的输出似乎不可能。我只能得到net_amount
payment table:
id | net_amount | payment_dt | person_id
1001 | 2765.36 | 2016-05-28 | 372
1002 | 2474.76 | 2016-05-29 | 372
1003 | 22694.25 | 2016-05-29 | 384
1004 | 1911.92 | 2016-05-29 | 384
discounts table:
id | person_id | gross_amount | sc_discount | other_discount_amount | other_discount_type
1 | 372 | 3566.7 | 713.34 | 88.00 | MISC
2 | 372 | 3202.2 | 640.44 | 87.00 | PAT
3 | 384 | 3566.7 | 713.34 | 285.34 | MISC
4 | 384 | 27953.10 | 5590.62 | 2236.25 | PAT
5 | 384 | 2655.45 | 531.09 | 212.44 | MISC
*1 - payment_dt is 2016-05-28
expected output: (where payment_dt=2016-05-29)
total_gross_amount | total_sc_discount | total_misc_discount | total_pat_discount | total_net_amount
37,377.45 | 7475.49 | 497.78 | 2,323.25 | 27,080.93
如果两个表的记录之间没有逻辑联系,则无法获得预期的结果。如果你可以指出,每天只有一个记录在dicount表中,并且这些日子还在继续......这意味着今天的折扣是最高的ID昨天是higestid减1 ,,,那么我们可以工作......但这是非常如果例如某一天缺失并打破该顺序,那么特定案例和非常危险。 – SMW
您能否更详细地解释您的模式: Q1:为什么付款表中的“id”重复? Q2:为什么有4个支付条目,但5个折扣条目,它应该是1-1映射? Q3:是net_amount = gross_amount - sc_discount - other_discount_amount? – greperror
这两张表之间可能有***关系。折扣1的'3566.70 - 713.34 - 88.00 = 2765.36'与支付表中的第一行相匹配。折扣2和折扣5的作品一样。然而,折扣3没有匹配的付款行。折扣4 *出现*与最大付款有关,但数字不相加。您似乎缺少一个*整个表格(或表格)*以将付款链接到折扣,或者至少是一些重要的字段。 – MatBailie