我有这两个表:
我需要使用折扣表加入付款表。由于折扣表没有付款日期,因此预计输出似乎不可能。我只能获得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
答案 0 :(得分:0)
正如我在两个表中看到的,共同列是person_id,您可以尝试加入它。有关更多信息,您可以考虑自然连接,在互联网上阅读它;)
" NATURAL JOIN是一个JOIN操作,它根据要连接的两个表中的公共列为您创建隐式连接子句。公共列是两个表中具有相同名称的列。 NATURAL JOIN可以是INNER连接,LEFT OUTER连接或RIGHT OUTER连接。默认为INNER连接。 "
答案 1 :(得分:0)
假设: net_amount = gross_amount - sc_discount - other_discount_amount
您无需在预期输出
中转到payment_net_amount的付款表你可以这样写:
Select sum(gross_amount) as total_gross_amount,
sum(sc_discount) as total_sc_discount,
sum(gross_amount - sc_discount - other_discount_amount) as total_net_amount
sum(CASE other_discount_type when 'MISC' THEN other_discount_amount WHEN 'PAT' THEN 0) as total_misc_discount,
sum(CASE other_discount_type when 'MISC' THEN 0 WHEN 'PAT' THEN other_discount_amount) as total_pat_discount
from discounts
如果上述假设不正确,由于聚合完成,输出中只有1行,您可以获得除上述查询中的total_net_amount之外的所有列,从payment表中获取sum(net_amount),并加入它们只有1,1行。