Showing posts with label SQL. Show all posts
Showing posts with label SQL. Show all posts

Wednesday, November 29, 2017

The UNION [ALL], INTERSECT, MINUS Operators

UNION Example The following statement combines the results of two queries with the UNION operator, which eliminates duplicate selected rows. This statement shows that you must match datatype (using the TO_CHAR function) when columns do not exist in one or the other table:
SELECT location_id, department_name "Department", 
   TO_CHAR(NULL) "Warehouse"  FROM departments
   UNION
   SELECT location_id, TO_CHAR(NULL) "Department", warehouse_name 
   FROM warehouses;
UNION ALL Example The UNION operator returns only distinct rows that appear in either result, while the UNION ALL operator returns all rows. The UNION ALL operator does not eliminate duplicate selected rows:
SELECT product_id FROM order_items
UNION
SELECT product_id FROM inventories;

SELECT location_id  FROM locations 
UNION ALL 
SELECT location_id  FROM departments;

A location_id value that appears multiple times in either or both queries (such as '1700') is returned only once by the UNION operator, but multiple times by the UNION ALL operator.
INTERSECT Example The following statement combines the results with the INTERSECT operator, which returns only those rows returned by both queries:
SELECT product_id FROM inventories
INTERSECT
SELECT product_id FROM order_items;
MINUS Example The following statement combines results with the MINUS operator, which returns only unique rows returned by the first query but not by the second:
SELECT product_id FROM inventories
MINUS
SELECT product_id FROM order_items;

Thursday, August 14, 2014

Top-N-SQL using RANK() and DENSE_RANK()DENSE_RANK()


RANK gives you the ranking within your ordered partition. Ties are assigned the same rank, with the next ranking(s) skipped. So, if you have 3 items at rank 2, the next rank listed would be ranked 5.
DENSE_RANK again gives you the ranking within your ordered partition, but the ranks are consecutive. No ranks are skipped if there are ranks with multiple items.

- using rank()
SELECT segment_name, bytes
  FROM ( SELECT segment_name, bytes, RANK() OVER (ORDER BY bytes DESC) sal_rank
           FROM user_segments )
 WHERE sal_rank <= 5;


 -- using dense_rank()

 SELECT segment_name, bytes
  FROM ( SELECT segment_name, bytes, DENSE_RANK() OVER (ORDER BY bytes DESC) sal_rank
           FROM user_segments )
 WHERE sal_rank <= 5;