Advertisement
srghma

Untitled

Jun 26th, 2018
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.13 KB | None | 0 0
  1. CREATE TABLE solicitations
  2. (
  3. id SERIAL PRIMARY KEY,
  4. name text
  5. );
  6.  
  7. CREATE TABLE donations
  8. (
  9. id SERIAL PRIMARY KEY,
  10. solicitation_id integer REFERENCES solicitations, -- can be null
  11. created_at timestamp without time zone NOT NULL DEFAULT (now() at time zone 'utc'),
  12. amount bigint NOT NULL DEFAULT 0
  13. );
  14.  
  15.  
  16. INSERT INTO solicitations (name) VALUES
  17. ('solicitation1'), ('solicitation2');
  18.  
  19. INSERT INTO donations (solicitation_id, amount) VALUES
  20. (null, 10), (1, 20), (2, 30);
  21.  
  22. SELECT
  23. "created_at"
  24. , COALESCE("no_solicitation", 0) AS "no_solicitation"
  25. , COALESCE("1", 0) AS "1"
  26. , COALESCE("2", 0) AS "2"
  27. FROM crosstab(
  28. $source_sql$
  29. SELECT
  30. created_at::date as row_id
  31. , COALESCE(solicitation_id::text, 'no_solicitation') as category
  32. , SUM(amount) as value
  33. FROM donations
  34. GROUP BY row_id, category
  35. ORDER BY row_id, category
  36. $source_sql$
  37. , $category_sql$
  38. SELECT 'no_solicitation' AS foo
  39. UNION ALL
  40. SELECT DISTINCT id::text AS foo FROM solicitations ORDER BY foo
  41. $category_sql$
  42. ) AS ct (
  43. "created_at" date
  44. , "no_solicitation" bigint
  45. , "1" bigint
  46. , "2" bigint
  47. )
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement