Advertisement
DataCCIW

Event Balance

Jun 14th, 2019
391
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
T-SQL 2.33 KB | None | 0 0
  1. With event_cost_payments AS
  2. (
  3. SELECT DISTINCT
  4. R.profile_id
  5. ,RC.person_id
  6. ,cost_payments = ISNULL(SUM(CP.payment_amount) OVER (PARTITION by R.profile_id, RC.person_id),0)
  7. ,cost_discounts = ((SELECT SUM(C.amount) FROM evnt_cost C WHERE C.profile_id IN (@event_id))
  8. * (R.discount_code_percentage + R.early_bird_discount_percentage + R.group_discount_percentage))
  9. + (R.discount_code_amount + R.early_bird_discount_amount + R.group_discount_amount)
  10. FROM evnt_registrant R
  11. LEFT JOIN evnt_registrant_cost RC ON RC.person_id = R.person_id AND RC.profile_id = R.profile_id
  12. LEFT JOIN evnt_registrant_cost_payment CP ON CP.registrant_cost_id = RC.registrant_cost_id
  13. WHERE R.profile_id IN (@event_id)
  14. ),
  15.  
  16. event_costs AS
  17. (
  18. SELECT DISTINCT
  19. E.profile_id
  20. ,event_cost = sum(C.amount) over (PARTITION by E.profile_id)
  21. FROM evnt_event_profile E
  22. JOIN evnt_cost C ON C.profile_id = E.profile_id
  23. WHERE E.profile_id IN (@event_id)
  24. ),
  25.  
  26. event_fees_payments AS
  27. (
  28. SELECT DISTINCT
  29. E.profile_id
  30. ,R.person_id
  31. ,fee_payment = SUM(FP.payment_amount) OVER (PARTITION by E.profile_id, R.person_id)
  32. FROM evnt_event_profile AS E
  33. LEFT JOIN evnt_registrant AS R ON E.profile_id = R.profile_id
  34. LEFT JOIN evnt_registrant_fee AS RF ON RF.person_id = R.person_id
  35. LEFT JOIN evnt_registrant_fee_payment FP ON FP.registrant_fee_id = RF.registrant_fee_id
  36. WHERE E.profile_id IN (@event_id)
  37. ),
  38.  
  39. event_fees AS
  40. (
  41. SELECT DISTINCT
  42. R.profile_id
  43. ,R.person_id
  44. ,fee_cost = ISNULL(SUM(RF.quantity * F.amount),0) --technically there could be fee discounts but these are rare because they typically lead to unintentionally giving someone double the discount intended
  45. FROM evnt_registrant AS R
  46. LEFT JOIN evnt_registrant_fee AS RF ON RF.person_id = R.person_id
  47. LEFT JOIN evnt_fee F on F.profile_id = R.profile_id
  48. WHERE R.profile_id IN (@event_id)
  49. GROUP BY R.profile_id, R.person_id
  50. ),
  51.  
  52. summary AS
  53. (
  54. SELECT
  55. C.profile_id
  56. ,C.event_cost
  57. ,CP.person_id
  58. ,CP.cost_payments
  59. ,CP.cost_discounts
  60. ,F.fee_cost
  61. ,fee_payment = COALESCE(FP.fee_Payment,0)
  62. FROM event_costs C
  63. LEFT join event_cost_payments CP on CP.profile_id = C.profile_id
  64. LEFT join event_fees F on F.profile_id = C.profile_id and F.person_id = CP.person_id
  65. LEFT join event_fees_payments FP on CP.person_id = FP.person_id
  66. )
  67.  
  68. SELECT *
  69. ,balance = event_cost - cost_payments - cost_discounts + fee_cost - fee_payment
  70. FROM summary
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement