Guest User

Untitled

a guest
Nov 16th, 2018
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.18 KB | None | 0 0
  1. WITH billed_by_courier AS (
  2. SELECT
  3. vendor_ref
  4. FROM
  5. accounting_vendor_billables
  6. INNER JOIN
  7. accounting_vendor_invoices ON accounting_vendor_invoices.id = accounting_vendor_billables.vendor_invoice_id
  8. WHERE
  9. accounting_vendor_invoices.type IN ('Accounting::VendorInvoices::UPS', 'Accounting::VendorInvoices::DPD')
  10. GROUP BY
  11. vendor_ref
  12. ), billed_by_via AS (
  13. SELECT
  14. (array_agg(date_trunc('day', accounting_billables.created_at)))[1] AS billed_at,
  15. vendor_ref,
  16. SUM(amount) AS sum_amount,
  17. (array_agg(last_mile_deliveries.service))[1] AS service
  18. FROM
  19. accounting_billables
  20. INNER JOIN
  21. last_mile_deliveries ON last_mile_deliveries.id = accounting_billables.parent_id AND accounting_billables.parent_type = 'LastMile::Delivery'
  22. WHERE
  23. last_mile_deliveries.service != 'FCE'
  24. AND accounting_billables.type NOT IN ('return_delivery', 'return_handling', 'relabel')
  25. AND accounting_billables.vendor_ref IS NOT NULL
  26. AND accounting_billables.created_at > NOW() - INTERVAL '90 days'
  27. GROUP BY vendor_ref
  28. )
  29.  
  30. SELECT
  31. *
  32. FROM
  33. billed_by_via
  34. WHERE
  35. NOT EXISTS (
  36. SELECT 1 FROM billed_by_courier WHERE billed_by_courier.vendor_ref = billed_by_via.vendor_ref
  37. )
Add Comment
Please, Sign In to add comment