Guest User

Untitled

a guest
Feb 21st, 2018
269
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.10 KB | None | 0 0
  1. \!h Example - convert years to months in producer list:
  2. SELECT producer_name, months FROM -- returns producer_name and months from the subquery
  3. -- subquery returns two columns, producer_name and months(alias for years multiplied by 12), from the producer table
  4. (SELECT producer_name, years*12 AS months FROM producer) AS prod; -- 2nd alias here needs to be included
  5. +---------------+--------+
  6. | producer_name | months |
  7. +---------------+--------+
  8. | Phil Spector | 432 |
  9. | George Martin | 480 |
  10. | Tina Weymouth | 240 |
  11. | Chris Frantz | 240 |
  12. | Ed Kuepper | 180 |
  13. +---------------+--------+
  14.  
  15. \!h Example 2 - average number of albums we own by each artist:
  16. -- avg of 'albums' subquery
  17. SELECT AVG(albums) FROM
  18. -- subquery returns no. of unique albums and aliases it 'albums'
  19. (SELECT COUNT(*) AS albums FROM artist INNER JOIN album
  20. USING (artist_id) GROUP BY artist.artist_id) AS alb;
  21. +-------------+
  22. | AVG(albums) |
  23. +-------------+
  24. | 2.1667 |
  25. +-------------+
  26. \!h These subqueries are a good way to apply two aggregate functions to one set of data
  27. -- This is because things like AVG(COUNT(*)) wont work.
Add Comment
Please, Sign In to add comment