SQL for Smarties | SQL Programming Style | Trees and Hierarchies in SQL | SQL Puzzles and Answers | Data and Databases


Thursday, June 14, 2007

Need urgent help on a QUERY

SQL Apprentice Question
Given:

SELECT STATE_ID
FROM GROUP_STATE


STATE_ID
----------------
10
15
16
17
18
19
20


SELECT GROUP_ID
FROM GROUP
WHERE GROUP_ID NOT IN (SELECT DISTINCT GROUP_ID FROM GROUP_STATE)


GROUP_ID
---------------
1
2
16
5


I need a query that would look like:
GROUP_ID STATE_ID
--------------- ----------------
1 10
1 15
1 16
1 17
1 18
1 19
1 20


2 10
2 15
2 16
2 17
2 18
2 19
2 20


ETC....



Celko Answers
SELECT GS.state_id, G.group_id
FROM ( SELECT state_id FROM GroupStates AS GS
CROSS JOIN
SELECT group_id FROM Groups
WHERE group_id
NOT IN (SELECT DISTINCT group_id FROM GroupStates)
AS G);

Do not use reserved words for data element names.


Original Source

No comments: