sql interview

21
(i) Finding the nth highest salary of an employee. Create a table named Employee_Test and insert some test data as:- Collapse | Copy Code CREATE TABLE Employee_Test ( Emp_ID INT Identity, Emp_name Varchar(100), Emp_Sal Decimal (10,2) ) INSERT INTO Employee_Test VALUES ('Anees',1000); INSERT INTO Employee_Test VALUES ('Rick',1200); INSERT INTO Employee_Test VALUES ('John',1100); INSERT INTO Employee_Test VALUES ('Stephen',1300); INSERT INTO Employee_Test VALUES ('Maria',1400); It is very easy to find the highest salary as:- Collapse | Copy Code --Highest Salary select max(Emp_Sal) from Employee_Test Now, if you are asked to find the 3rd highest salary, then the query is as:- Collapse | Copy Code --3rd Highest Salary select min(Emp_Sal) from Employee_Test where Emp_Sal in (select distinct top 3 Emp_Sal from Employee_Test order by Emp_Sal desc) The result is as :- 1200 To find the nth highest salary, replace the top 3 with top n (n being an integer 1,2,3 etc.) Collapse | Copy Code --nth Highest Salary select min(Emp_Sal) from Employee_Test where Emp_Sal in (select distinct top n Emp_Sal from Employee_Test order by Emp_Sal desc) (ii) Finding TOP X records from each group Create a table named photo_test and insert some test data as :- Collapse | Copy Code create table photo_test ( pgm_main_Category_id int, pgm_sub_category_id int, file_path varchar(MAX) ) insert into photo_test values (17,15,'photo/bb1.jpg');

Upload: hundet

Post on 27-Oct-2014

57 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: SQL Interview

(i) Finding the nth highest salary of an employee.

Create a table named Employee_Test and insert some test data as:- Collapse | Copy Code

CREATE TABLE Employee_Test(Emp_ID INT Identity,Emp_name Varchar(100),Emp_Sal Decimal (10,2))

INSERT INTO Employee_Test VALUES ('Anees',1000);INSERT INTO Employee_Test VALUES ('Rick',1200);INSERT INTO Employee_Test VALUES ('John',1100);INSERT INTO Employee_Test VALUES ('Stephen',1300);INSERT INTO Employee_Test VALUES ('Maria',1400);

It is very easy to find the highest salary as:- Collapse | Copy Code

--Highest Salaryselect max(Emp_Sal) from Employee_Test

Now, if you are asked to find the 3rd highest salary, then the query is as:- Collapse | Copy Code

--3rd Highest Salaryselect min(Emp_Sal) from Employee_Test where Emp_Sal in(select distinct top 3 Emp_Sal from Employee_Test order by Emp_Sal desc)

The result is as :- 1200 To find the nth highest salary, replace the top 3 with top n (n being an integer 1,2,3 etc.)

Collapse | Copy Code

--nth Highest Salaryselect min(Emp_Sal) from Employee_Test where Emp_Sal in(select distinct top n Emp_Sal from Employee_Test order by Emp_Sal desc)

(ii) Finding TOP X records from each group

Create a table named photo_test and insert some test data as :- Collapse | Copy Code

create table photo_test(pgm_main_Category_id int,pgm_sub_category_id int,file_path varchar(MAX))

insert into photo_test values(17,15,'photo/bb1.jpg'); insert into photo_test values(17,16,'photo/cricket1.jpg'); insert into photo_test values(17,17,'photo/base1.jpg'); insert into photo_test values(18,18,'photo/forest1.jpg'); insert into photo_test values(18,19,'photo/tree1.jpg'); insert into photo_test values(18,20,'photo/flower1.jpg'); insert into photo_test values(19,21,'photo/laptop1.jpg'); insert into photo_test values(19,22,'photo/camer1.jpg');

insert into photo_test values(19,23,'photo/cybermbl1.jpg'); insert into photo_test values

Page 2: SQL Interview

(17,24,'photo/F1.jpg');

There are three groups of pgm_main_category_id each with a value of 17 (group 17 has four records),18 (group 18 has three records) and 19 (group 19 has three records). Now, if you want to select top 2 records from each group, the query is as follows:-

Collapse | Copy Code

select pgm_main_category_id,pgm_sub_category_id,file_path from(select pgm_main_category_id,pgm_sub_category_id,file_path,rank() over (partition by pgm_main_category_id order by pgm_sub_category_id asc) as rankidfrom photo_test) photo_testwhere rankid < 3 -- replace 3 by any number 2,3 etc for top2 or top3.order by pgm_main_category_id,pgm_sub_category_id

The result is as:- Collapse | Copy Code

pgm_main_category_id pgm_sub_category_id file_path17 15 photo/bb1.jpg17 16 photo/cricket1.jpg18 18 photo/forest1.jpg18 19 photo/tree1.jpg19 21 photo/laptop1.jpg19 22 photocamer1.jpg

(iii) Deleting duplicate rows from a table

A table with a primary key doesn’t contain duplicates. But if due to some reason, the keys have to be disabled or when importing data from other sources, duplicates come up in the table data, it is often needed to get rid of such duplicates. This can be achieved in tow ways :- (a) Using a temporary table. (b) Without using a temporary table.

(a) Using a temporary or staging table

Let the table employee_test1 contain some duplicate data like:- Collapse | Copy Code

CREATE TABLE Employee_Test1(Emp_ID INT,Emp_name Varchar(100),Emp_Sal Decimal (10,2))

INSERT INTO Employee_Test1 VALUES (1,'Anees',1000);INSERT INTO Employee_Test1 VALUES (2,'Rick',1200);INSERT INTO Employee_Test1 VALUES (3,'John',1100);INSERT INTO Employee_Test1 VALUES (4,'Stephen',1300);INSERT INTO Employee_Test1 VALUES (5,'Maria',1400);INSERT INTO Employee_Test1 VALUES (6,'Tim',1150);INSERT INTO Employee_Test1 VALUES (6,'Tim',1150);

Step 1: Create a temporary table from the main table as:- Collapse | Copy Code

Page 3: SQL Interview

select top 0* into employee_test1_temp from employee_test1

Step2 : Insert the result of the GROUP BY query into the temporary table as:- Collapse | Copy Code

insert into employee_test1_tempselect Emp_ID,Emp_name,Emp_Salfrom employee_test1group by Emp_ID,Emp_name,Emp_Sal

Step3: Truncate the original table as:- Collapse | Copy Code

truncate table employee_test1

Step4: Fill the original table with the rows of the temporary table as:- Collapse | Copy Code

insert into employee_test1select * from employee_test1_temp

Now, the duplicate rows from the main table have been removed. Collapse | Copy Code

select * from employee_test1

gives the result as:- Collapse | Copy Code

Emp_ID Emp_name Emp_Sal1 Anees 10002 Rick 12003 John 11004 Stephen 13005 Maria 14006 Tim 1150

(b) Without using a temporary table

Collapse | Copy Code

;with T as(

select * , row_number() over (partition by Emp_ID order by Emp_ID) as rankfrom employee_test1

)

deletefrom Twhere rank > 1

The result is as:- Collapse | Copy Code

Emp_ID Emp_name Emp_Sal1 Anees 10002 Rick 12003 John 11004 Stephen 13005 Maria 14006 Tim 1150

Page 4: SQL Interview

1. To fetch ALTERNATE records from a table. (EVEN NUMBERED)

select * from emp where rowid in (select decode(mod(rownum,2),0,rowid, null) from emp);

2. To select ALTERNATE records from a table. (ODD NUMBERED)

select * from emp where rowid in (select decode(mod(rownum,2),0,null ,rowid) from emp);

3. Find the 3rd MAX salary in the emp table.

select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2 where e1.sal <=

e2.sal);

4. Find the 3rd MIN salary in the emp table.

select distinct sal from emp e1 where 3 = (select count(distinct sal) from emp e2where e1.sal >=

e2.sal);

5. Select FIRST n records from a table.

select * from emp where rownum <= &n;

6. Select LAST n records from a table

select * from emp minus select * from emp where rownum <= (select count(*) - &n from emp);

7. List dept no., Dept name for all the departments in which there are no employees in

the department.

select * from dept where deptno not in (select deptno from emp);  

alternate solution:  select * from dept a where not exists (select * from emp b where a.deptno =

b.deptno);

altertnate solution:  select empno,ename,b.deptno,dname from emp a, dept b where a.deptno(+)

= b.deptno and empno is null;

8. How to get 3 Max salaries ?

select distinct sal from emp a where 3 >= (select count(distinct sal) from emp b where a.sal <=

b.sal) order by a.sal desc;

9. How to get 3 Min salaries ?

select distinct sal from emp a  where 3 >= (select count(distinct sal) from emp b  where a.sal >=

b.sal);

10. How to get nth max salaries ?

select distinct hiredate from emp a where &n =  (select count(distinct sal) from emp b where a.sal

>= b.sal);

Page 5: SQL Interview

11. Select DISTINCT RECORDS from emp table.

select * from emp a where  rowid = (select max(rowid) from emp b where  a.empno=b.empno);

12. How to delete duplicate rows in a table?

delete from emp a where rowid != (select max(rowid) from emp b where  a.empno=b.empno);

13. Count of number of employees in  department  wise.

select count(EMPNO), b.deptno, dname from emp a, dept b  where a.deptno(+)=b.deptno  group

by b.deptno,dname;

14.  Suppose there is annual salary information provided by emp table. How to fetch

monthly salary of each and every employee?

select ename,sal/12 as monthlysal from emp;

15. Select all record from emp table where deptno =10 or 40.

select * from emp where deptno=30 or deptno=10;

16. Select all record from emp table where deptno=30 and sal>1500.

select * from emp where deptno=30 and sal>1500;

17. Select  all record  from emp where job not in SALESMAN  or CLERK.

select * from emp where job not in ('SALESMAN','CLERK');

18. Select all record from emp where ename in 'BLAKE','SCOTT','KING'and'FORD'.

select * from emp where ename in('JONES','BLAKE','SCOTT','KING','FORD');

19. Select all records where ename starts with ‘S’ and its lenth is 6 char.

select * from emp where ename like'S____';

20. Select all records where ename may be any no of  character but it should end with

‘R’.

select * from emp where ename like'%R';

21. Count  MGR and their salary in emp table.

Page 6: SQL Interview

select count(MGR),count(sal) from emp;

22. In emp table add comm+sal as total sal  .

select ename,(sal+nvl(comm,0)) as totalsal from emp;

23. Select  any salary <3000 from emp table. 

select * from emp  where sal> any(select sal from emp where sal<3000);

24. Select  all salary <3000 from emp table. 

select * from emp  where sal> all(select sal from emp where sal<3000);

25. Select all the employee  group by deptno and sal in descending order.

select ename,deptno,sal from emp order by deptno,sal desc;

26. How can I create an empty table emp1 with same structure as emp?

Create table emp1 as select * from emp where 1=2;

27. How to retrive record where sal between 1000 to 2000?

Select * from emp where sal>=1000 And  sal<2000

28. Select all records where dept no of both emp and dept table matches.

select * from emp where exists(select * from dept where emp.deptno=dept.deptno)

29. If there are two tables emp1 and emp2, and both have common record. How can I

fetch all the recods but common records only once?

(Select * from emp) Union (Select * from emp1)

30. How to fetch only common records from two tables emp and emp1?

(Select * from emp) Intersect (Select * from emp1)

31.  How can I retrive all records of emp1 those should not present in emp2?

(Select * from emp) Minus (Select * from emp1)

32. Count the totalsa  deptno wise where more than 2 employees exist.

SELECT  deptno, sum(sal) As totalsal

FROM emp

Page 7: SQL Interview

GROUP BY deptno

HAVING COUNT(empno) > 2

Interview Questions - Part 5

Write SQL queries for the below interview questions:

1. Load the below products table into the target table.

CREATE TABLE PRODUCTS( PRODUCT_ID INTEGER, PRODUCT_NAME VARCHAR2(30));

INSERT INTO PRODUCTS VALUES ( 100, 'Nokia');INSERT INTO PRODUCTS VALUES ( 200, 'IPhone');INSERT INTO PRODUCTS VALUES ( 300, 'Samsung');INSERT INTO PRODUCTS VALUES ( 400, 'LG');INSERT INTO PRODUCTS VALUES ( 500, 'BlackBerry');INSERT INTO PRODUCTS VALUES ( 600, 'Motorola');COMMIT;

SELECT * FROM PRODUCTS;

PRODUCT_ID PRODUCT_NAME-----------------------100 Nokia200 IPhone300 Samsung400 LG500 BlackBerry600 Motorola

The requirements for loading the target table are:

Select only 2 products randomly. Do not select the products which are already loaded in the target table with in the last 30

days.

Target table should always contain the products loaded in 30 days. It should not contain the products which are loaded prior to 30 days.

Solution:

First we will create a target table. The target table will have an additional column INSERT_DATE to know when a product is loaded into the target table. The target table structure is

Page 8: SQL Interview

CREATE TABLE TGT_PRODUCTS( PRODUCT_ID INTEGER, PRODUCT_NAME VARCHAR2(30), INSERT_DATE DATE);

The next step is to pick 5 products randomly and then load into target table. While selecting check whether the products are there in the

INSERT INTO TGT_PRODUCTSSELECT PRODUCT_ID, PRODUCT_NAME, SYSDATE INSERT_DATEFROM(SELECT PRODUCT_ID, PRODUCT_NAMEFROM PRODUCTS SWHERE NOT EXISTS ( SELECT 1 FROM TGT_PRODUCTS T WHERE T.PRODUCT_ID = S.PRODUCT_ID )ORDER BY DBMS_RANDOM.VALUE --Random number generator in oracle.)AWHERE ROWNUM <= 2;

The last step is to delete the products from the table which are loaded 30 days back.

DELETE FROM TGT_PRODUCTSWHERE INSERT_DATE < SYSDATE - 30;

2. Load the below CONTENTS table into the target table.

CREATE TABLE CONTENTS( CONTENT_ID INTEGER, CONTENT_TYPE VARCHAR2(30));

INSERT INTO CONTENTS VALUES (1,'MOVIE');INSERT INTO CONTENTS VALUES (2,'MOVIE');INSERT INTO CONTENTS VALUES (3,'AUDIO');INSERT INTO CONTENTS VALUES (4,'AUDIO');INSERT INTO CONTENTS VALUES (5,'MAGAZINE');INSERT INTO CONTENTS VALUES (6,'MAGAZINE');COMMIT;

SELECT * FROM CONTENTS;

CONTENT_ID CONTENT_TYPE-----------------------

Page 9: SQL Interview

1 MOVIE2 MOVIE3 AUDIO4 AUDIO5 MAGAZINE6 MAGAZINE

The requirements to load the target table are:

Load only one content type at a time into the target table. The target table should always contain only one contain type.

The loading of content types should follow round-robin style. First MOVIE, second AUDIO, Third MAGAZINE and again fourth Movie.

Solution:

First we will create a lookup table where we mention the priorities for the content types. The lookup table “Create Statement” and data is shown below.

CREATE TABLE CONTENTS_LKP( CONTENT_TYPE VARCHAR2(30), PRIORITY INTEGER, LOAD_FLAG INTEGER);

INSERT INTO CONTENTS_LKP VALUES('MOVIE',1,1);INSERT INTO CONTENTS_LKP VALUES('AUDIO',2,0);INSERT INTO CONTENTS_LKP VALUES('MAGAZINE',3,0);COMMIT;

SELECT * FROM CONTENTS_LKP;

CONTENT_TYPE PRIORITY LOAD_FLAG---------------------------------MOVIE 1 1AUDIO 2 0MAGAZINE 3 0

Here if LOAD_FLAG is 1, then it indicates which content type needs to be loaded into the target table. Only one content type will have LOAD_FLAG as 1. The other content types will have LOAD_FLAG as 0. The target table structure is same as the source table structure.

The second step is to truncate the target table before loading the data

TRUNCATE TABLE TGT_CONTENTS;

Page 10: SQL Interview

The third step is to choose the appropriate content type from the lookup table to load the source data into the target table.

INSERT INTO TGT_CONTENTSSELECT CONTENT_ID, CONTENT_TYPE FROM CONTENTSWHERE CONTENT_TYPE = (SELECT CONTENT_TYPE FROM CONTENTS_LKP WHERE LOAD_FLAG=1);

The last step is to update the LOAD_FLAG of the Lookup table.

UPDATE CONTENTS_LKPSET LOAD_FLAG = 0WHERE LOAD_FLAG = 1;

UPDATE CONTENTS_LKPSET LOAD_FLAG = 1WHERE PRIORITY = (SELECT DECODE( PRIORITY,(SELECT MAX(PRIORITY) FROM CONTENTS_LKP) ,1 , PRIORITY+1)FROM CONTENTS_LKPWHERE CONTENT_TYPE = (SELECT DISTINCT CONTENT_TYPE FROM TGT_CONTENTS));

Interview Questions - Oracle Part 1

As a database developer, writing SQL queries, PLSQL code is part of daily life. Having a good knowledge on SQL is really important. Here i am posting some practical examples on SQL queries.

To solve these interview questions on SQL queries you have to create the products, sales tables in your oracle database. The "Create Table", "Insert" statements are provided below.

CREATE TABLE PRODUCTS( PRODUCT_ID INTEGER, PRODUCT_NAME VARCHAR2(30));CREATE TABLE SALES( SALE_ID INTEGER, PRODUCT_ID INTEGER, YEAR INTEGER, Quantity INTEGER, PRICE INTEGER);

INSERT INTO PRODUCTS VALUES ( 100, 'Nokia');INSERT INTO PRODUCTS VALUES ( 200, 'IPhone');INSERT INTO PRODUCTS VALUES ( 300, 'Samsung');INSERT INTO PRODUCTS VALUES ( 400, 'LG');

INSERT INTO SALES VALUES ( 1, 100, 2010, 25, 5000);INSERT INTO SALES VALUES ( 2, 100, 2011, 16, 5000);

Page 11: SQL Interview

INSERT INTO SALES VALUES ( 3, 100, 2012, 8, 5000);INSERT INTO SALES VALUES ( 4, 200, 2010, 10, 9000);INSERT INTO SALES VALUES ( 5, 200, 2011, 15, 9000);INSERT INTO SALES VALUES ( 6, 200, 2012, 20, 9000);INSERT INTO SALES VALUES ( 7, 300, 2010, 20, 7000);INSERT INTO SALES VALUES ( 8, 300, 2011, 18, 7000);INSERT INTO SALES VALUES ( 9, 300, 2012, 20, 7000);COMMIT;

The products table contains the below data.

SELECT * FROM PRODUCTS;

PRODUCT_ID PRODUCT_NAME-----------------------100 Nokia200 IPhone300 Samsung

The sales table contains the following data.

SELECT * FROM SALES;

SALE_ID PRODUCT_ID YEAR QUANTITY PRICE--------------------------------------1 100 2010 25 50002 100 2011 16 50003 100 2012 8 50004 200 2010 10 90005 200 2011 15 90006 200 2012 20 90007 300 2010 20 70008 300 2011 18 70009 300 2012 20 7000

Here Quantity is the number of products sold in each year. Price is the sale price of each product.

I hope you have created the tables in your oracle database. Now try to solve the below SQL queries.

1. Write a SQL query to find the products which have continuous increase in sales every year?

Solution:

Here “Iphone” is the only product whose sales are increasing every year.

STEP1: First we will get the previous year sales for each product. The SQL query to do this is

SELECT P.PRODUCT_NAME, S.YEAR, S.QUANTITY, LEAD(S.QUANTITY,1,0) OVER ( PARTITION BY P.PRODUCT_ID

Page 12: SQL Interview

ORDER BY S.YEAR DESC ) QUAN_PREV_YEARFROM PRODUCTS P, SALES SWHERE P.PRODUCT_ID = S.PRODUCT_ID;

PRODUCT_NAME YEAR QUANTITY QUAN_PREV_YEAR-----------------------------------------Nokia 2012 8 16Nokia 2011 16 25Nokia 2010 25 0IPhone 2012 20 15IPhone 2011 15 10IPhone 2010 10 0Samsung 2012 20 18Samsung 2011 18 20Samsung 2010 20 0

Here the lead analytic function will get the quantity of a product in its previous year.

STEP2: We will find the difference between the quantities of a product with its previous year’s quantity. If this difference is greater than or equal to zero for all the rows, then the product is a constantly increasing in sales. The final query to get the required result is

SELECT PRODUCT_NAMEFROM(SELECT P.PRODUCT_NAME, S.QUANTITY - LEAD(S.QUANTITY,1,0) OVER ( PARTITION BY P.PRODUCT_ID ORDER BY S.YEAR DESC ) QUAN_DIFFFROM PRODUCTS P, SALES SWHERE P.PRODUCT_ID = S.PRODUCT_ID)AGROUP BY PRODUCT_NAMEHAVING MIN(QUAN_DIFF) >= 0;

PRODUCT_NAME------------IPhone

2. Write a SQL query to find the products which does not have sales at all?

Solution:

“LG” is the only product which does not have sales at all. This can be achieved in three ways.

Method1: Using left outer join.

Page 13: SQL Interview

SELECT P.PRODUCT_NAMEFROM PRODUCTS P LEFT OUTER JOIN SALES SON (P.PRODUCT_ID = S.PRODUCT_ID);WHERE S.QUANTITY IS NULL

PRODUCT_NAME------------LG

Method2: Using the NOT IN operator.

SELECT P.PRODUCT_NAMEFROM PRODUCTS PWHERE P.PRODUCT_ID NOT IN (SELECT DISTINCT PRODUCT_ID FROM SALES);

PRODUCT_NAME------------LG

Method3: Using the NOT EXISTS operator.

SELECT P.PRODUCT_NAMEFROM PRODUCTS PWHERE NOT EXISTS (SELECT 1 FROM SALES S WHERE S.PRODUCT_ID = P.PRODUCT_ID);

PRODUCT_NAME------------LG

3. Write a SQL query to find the products whose sales decreased in 2012 compared to 2011?

Solution:

Here Nokia is the only product whose sales decreased in year 2012 when compared with the sales in the year 2011. The SQL query to get the required output is

SELECT P.PRODUCT_NAMEFROM PRODUCTS P, SALES S_2012, SALES S_2011WHERE P.PRODUCT_ID = S_2012.PRODUCT_IDAND S_2012.YEAR = 2012AND S_2011.YEAR = 2011AND S_2012.PRODUCT_ID = S_2011.PRODUCT_IDAND S_2012.QUANTITY < S_2011.QUANTITY;

PRODUCT_NAME------------Nokia

Page 14: SQL Interview

4. Write a query to select the top product sold in each year?

Solution:

Nokia is the top product sold in the year 2010. Similarly, Samsung in 2011 and IPhone, Samsung in 2012. The query for this is

SELECT PRODUCT_NAME, YEARFROM(SELECT P.PRODUCT_NAME, S.YEAR, RANK() OVER ( PARTITION BY S.YEAR ORDER BY S.QUANTITY DESC ) RNKFROM PRODUCTS P, SALES SWHERE P.PRODUCT_ID = S.PRODUCT_ID) AWHERE RNK = 1;

PRODUCT_NAME YEAR--------------------Nokia 2010Samsung 2011IPhone 2012Samsung 2012

5. Write a query to find the total sales of each product.?

Solution:

This is a simple query. You just need to group by the data on PRODUCT_NAME and then find the sum of sales.

SELECT P.PRODUCT_NAME, NVL( SUM( S.QUANTITY*S.PRICE ), 0) TOTAL_SALESFROM PRODUCTS P LEFT OUTER JOIN SALES SON (P.PRODUCT_ID = S.PRODUCT_ID)GROUP BY P.PRODUCT_NAME;

PRODUCT_NAME TOTAL_SALES---------------------------LG 0IPhone 405000Samsung 406000Nokia 245000

Page 15: SQL Interview

Interview Questions - Oracle Part 2

This is continuation to my previous post, SQL Queries Interview Questions - Oracle Part 1 , Where i have used PRODUCTS and SALES tables as an example. Here also i am using the same tables. So, just take a look at the tables by going through that link and it will be easy for you to understand the questions mentioned here.

Solve the below examples by writing SQL queries.

1. Write a query to find the products whose quantity sold in a year should be greater than the average quantity of the product sold across all the years?

Solution:

This can be solved with the help of correlated query. The SQL query for this is

SELECT P.PRODUCT_NAME, S.YEAR, S.QUANTITYFROM PRODUCTS P, SALES SWHERE P.PRODUCT_ID = S.PRODUCT_IDAND S.QUANTITY > (SELECT AVG(QUANTITY) FROM SALES S1 WHERE S1.PRODUCT_ID = S.PRODUCT_ID );

PRODUCT_NAME YEAR QUANTITY--------------------------Nokia 2010 25IPhone 2012 20Samsung 2012 20Samsung 2010 20

2. Write a query to compare the products sales of "IPhone" and "Samsung" in each year? The output should look like as

YEAR IPHONE_QUANT SAM_QUANT IPHONE_PRICE SAM_PRICE---------------------------------------------------2010 10 20 9000 70002011 15 18 9000 70002012 20 20 9000 7000

Solution:

By using self-join SQL query we can get the required result. The required SQL query is

SELECT S_I.YEAR, S_I.QUANTITY IPHONE_QUANT, S_S.QUANTITY SAM_QUANT,

Page 16: SQL Interview

S_I.PRICE IPHONE_PRICE, S_S.PRICE SAM_PRICEFROM PRODUCTS P_I, SALES S_I, PRODUCTS P_S, SALES S_SWHERE P_I.PRODUCT_ID = S_I.PRODUCT_IDAND P_S.PRODUCT_ID = S_S.PRODUCT_IDAND P_I.PRODUCT_NAME = 'IPhone'AND P_S.PRODUCT_NAME = 'Samsung'AND S_I.YEAR = S_S.YEAR

3. Write a query to find the ratios of the sales of a product?

Solution:

The ratio of a product is calculated as the total sales price in a particular year divide by the total sales price across all years. Oracle provides RATIO_TO_REPORT analytical function for finding the ratios. The SQL query is

SELECT P.PRODUCT_NAME, S.YEAR, RATIO_TO_REPORT(S.QUANTITY*S.PRICE) OVER(PARTITION BY P.PRODUCT_NAME ) SALES_RATIOFROM PRODUCTS P, SALES SWHERE (P.PRODUCT_ID = S.PRODUCT_ID);

PRODUCT_NAME YEAR RATIO-----------------------------IPhone 2011 0.333333333IPhone 2012 0.444444444IPhone 2010 0.222222222Nokia 2012 0.163265306Nokia 2011 0.326530612Nokia 2010 0.510204082Samsung 2010 0.344827586Samsung 2012 0.344827586Samsung 2011 0.310344828

4. In the SALES table quantity of each product is stored in rows for every year. Now write a query to transpose the quantity for each product and display it in columns? The output should look like as

PRODUCT_NAME QUAN_2010 QUAN_2011 QUAN_2012------------------------------------------IPhone 10 15 20Samsung 20 18 20Nokia 25 16 8

Solution:

Oracle 11g provides a pivot function to transpose the row data into column data. The SQL query for this is

Page 17: SQL Interview

SELECT * FROM(SELECT P.PRODUCT_NAME, S.QUANTITY, S.YEARFROM PRODUCTS P, SALES SWHERE (P.PRODUCT_ID = S.PRODUCT_ID))APIVOT ( MAX(QUANTITY) AS QUAN FOR (YEAR) IN (2010,2011,2012));

If you are not running oracle 11g database, then use the below query for transposing the row data into column data.

SELECT P.PRODUCT_NAME, MAX(DECODE(S.YEAR,2010, S.QUANTITY)) QUAN_2010, MAX(DECODE(S.YEAR,2011, S.QUANTITY)) QUAN_2011, MAX(DECODE(S.YEAR,2012, S.QUANTITY)) QUAN_2012FROM PRODUCTS P, SALES SWHERE (P.PRODUCT_ID = S.PRODUCT_ID)GROUP BY P.PRODUCT_NAME;

5. Write a query to find the number of products sold in each year?

Solution:

To get this result we have to group by on year and the find the count. The SQL query for this question is

SELECT YEAR, COUNT(1) NUM_PRODUCTSFROM SALESGROUP BY YEAR;

YEAR NUM_PRODUCTS------------------2010 32011 32012 3