Travis Tang

Singapore
Travis Tang

SQL

CUBE+GROUP BY for Subtotals

We all have used GROUP BY, but do you know CUBE? For example, if I have a table of user spending, I can get the subtotal of each user AND the total spend of all users combined, all within one table. πŸ“Œ Syntax is here. πš‚π™΄π™»π™΄π™²πšƒ πšžπšœπšŽπš›_πš’πš, πš‚πš„π™Ό(πšœπš™πšŽπš—πš) πšŠπš–πš π™΅πšπ™Ύπ™Ό πšžπšœπšŽπš›πšœ π™Άπšπ™Ύπš„π™Ώ π™±πšˆ π™²πš„π™±π™΄(πšžπšœπšŽπš›_πš’πš) This saves you the need to

SQL

Get subtotals with ROLLUP+GROUP BY

π™π™Šπ™‡π™‡π™π™‹ generates extra rows that represent the subtotals. For example… To get the sum of spending of each user, you typically GROUP BY user_id and SUM spend. Want to get the sum of ALL users in the same result? Try ROLLUP. πŸ“Œ The syntax is here. πš‚π™΄π™»π™΄π™²πšƒ πš„πšœπšŽπš›_πš’πš, πš‚πš„π™Ό(πšœπš™πšŽπš—πš) π™΅πšπ™Ύπ™Ό πš„πšœπšŽπš›πšœ π™Άπšπ™Ύπš„π™Ώ π™±πšˆ πšπ™Ύπ™»π™»πš„π™Ώ(πšžπšœπšŽπš›_πš’πš) The result will contain a

SQL

CROSS JOIN for all combinations

It is the cartesian products of both tables, if you're a math nerd. πŸ“Œ Syntax: πš‚π™΄π™»π™΄π™²πšƒ * π™΅πšπ™Ύπ™Ό πšπšŠπš‹πš•πšŽ_𝟷 π™²πšπ™Ύπš‚πš‚ 𝙹𝙾𝙸𝙽 πšπšŠπš‹πš•πšŽ_𝟸 Note that there is no need for an ON clause. CROSS JOIN is useful for getting all combinations - Matching users with all dates. - Match product tables with color tables to get product