Guest User

Untitled

a guest
Nov 16th, 2018
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 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.vendor_ref IS NOT NULL
  25. AND accounting_billables.created_at > NOW() - INTERVAL '90 days'
  26. GROUP BY vendor_ref
  27. )
  28.  
  29. SELECT
  30. SUM(sum_amount)
  31. FROM
  32. billed_by_via
  33. WHERE
  34. NOT EXISTS (
  35. SELECT 1 FROM billed_by_courier WHERE billed_by_courier.vendor_ref = billed_by_via.vendor_ref
  36. )
  37. GROUP BY service
Add Comment
Please, Sign In to add comment