Page 43 - SQL
P. 43

RosterEnd,
                CASE TeamA WHEN 1 THEN 'RR' WHEN 2 THEN 'DS' WHEN 3 THEN 'NS' END AS TeamA,
                CASE TeamB WHEN 1 THEN 'RR' WHEN 2 THEN 'DS' WHEN 3 THEN 'NS' END AS TeamB,
                CASE TeamC WHEN 1 THEN 'RR' WHEN 2 THEN 'DS' WHEN 3 THEN 'NS' END AS TeamC
         FROM roster


        Result


        I.e. For Week 1 TeamA is on R&R, TeamB is on Day Shift and TeamC is on Night Shift.

















        Refactoring a query to use Common Table Expressions


        Suppose we want to get all product categories with total sales greater than 20.

        Here is a query without Common Table Expressions:


         SELECT category.description, sum(product.price) as total_sales
         FROM sale
         LEFT JOIN product on sale.product_id = product.id
         LEFT JOIN category on product.category_id = category.id
         GROUP BY category.id, category.description
         HAVING sum(product.price) > 20


        And an equivalent query using Common Table Expressions:


         WITH all_sales AS (
           SELECT product.price, category.id as category_id, category.description as
         category_description
           FROM sale
           LEFT JOIN product on sale.product_id = product.id
           LEFT JOIN category on product.category_id = category.id
         )
         , sales_by_category AS (
           SELECT category_description, sum(price) as total_sales
           FROM all_sales
           GROUP BY category_id, category_description
         )
         SELECT * from sales_by_category WHERE total_sales > 20


        Example of a complex SQL with Common Table Expression


        Suppose we want to query the "cheapest products" from the "top categories".


        Here is an example of query using Common Table Expressions




        https://riptutorial.com/                                                                               25
   38   39   40   41   42   43   44   45   46   47   48