Db2 interview question on sql query.Explains GROUP BY and CASE Statement.
1. DB2 interview question on SQL Query
This question is asked by one of the blog reader and the question is as below:
Table Name : Item
ItemIDItemName...
1 A
2 B
3 C
Table Name : Purchase
PurOrdNumItemID
45671 1
45672 3
45673 1
45674 1
45675 2
45676 3
45677 1
45678 1
Expected Output:
ItemIDItemNameItemsSoldMoreThanOnceIndicator
1 A 5 Y
3 C 2 Y
2 B 1 N
Solution:
There are two tables and they need to be matched against Item id and if they match,we need
to find how many times that combination has appeared in purchase table.Once done we
need to move Y if the count is more than 1 and N if the the count is 1 to the indicator.
The count can be achieved by joining the tables and by using GROUP BY.
Have used table names as
item table as ITEMTBL
Purchase table as PURTBL
The Query will look as below
SELECT
A.ITEMID ITM,
A.ITEMNAME ITMNAME,
COUNT(*) COUNT
FROM
ITEMTBL A,
PURTBL B
WHERE A.ITEMID = B.ITEMID
GROUP BY A.ITEMID,A.ITEMNAME
This will give the output as below:
---------+---------+-----
ITM ITMNAME COUNT
---------+---------+-----
2. 1 A 5
2 B 1
3 C 2
But we cannot decide on the indicator in the same query as GROUP BY expects all columns
to be there with GROUP BY should only be there in SELECT .
If we have more columns in SELECT and all are not mentioned in GROUP BY then query
will not run and it will give you an error.
So have decided to use the above query as sub query and tried to derive the indicator based
on the count.
The final Query will look like as below:
SELECT ITM,ITMNAME,COUNT,
CASE COUNT
WHEN 1 THEN 'N'
ELSE 'Y'
END INDICATOR
FROM
(SELECT
A.ITEMID ITM,
A.ITEMNAME ITMNAME,
COUNT(*) COUNT
FROM
ITEMTBL A,
PURTBL B
WHERE A.ITEMID = B.ITEMID
GROUP BY A.ITEMID,A.ITEMNAME) AS TBL
CASE statement will derive the indicator as we expect based on the count field.
The output will be as below:
---------+---------+---------+---------+--
ITM ITMNAME COUNT INDICATOR
---------+---------+---------+---------+--
1 A 5 Y
2 B 1 N
3 C 2 Y
This query helps us to understand GROUP BY statement,considering sub query as a result
table and usage of CASE statement to derive some field based on any of the available
columns.
There is another way of achieving the same and same can be found in
http://clearmainframeinterview.blogspot.com/