Question : Help with pivot tables in SQL

I'm having a hard time wrapping my head around the sql PIVOT function.  I'd appreciate some help with a few examples.  

First, lets say I have a table called Perinatal that has the Sex and Date of birth and I want this output:
---------------------------
Date of Birth     M   F
---------------------------
1/1/2001          2   4
1/3/2001          5   2
1/5/2001          7   3
1/8/2001          1   2

How would I do that with the PIVOT statement?

I have 2 more samples too.

First, lets say perinatal has 2 fields, Sex and Nicu and I want to produce this where I count the sexes per nicu:

NICU   M    F
1        12  14
2         23  21
3         45  23

and to take this one a step farther, lets say I want to join that to the NICU table where NICU=ID of the Nicu table and Description is the fiedl I want like this:
NICU             M    F
Room A        12  14
Room B        23  21
Room C        45  23

Answer : Help with pivot tables in SQL


WITH x AS
(
SELECT ROWNUM seq, id1, flag
FROM (SELECT id1, flag,
CASE flag
WHEN 'F'
THEN 1
WHEN 'M'
THEN 2
ELSE 3
END cntr
FROM a) a,
TABLE (CAST (MULTISET (SELECT cntr + LEVEL - 1
FROM DUAL
CONNECT BY LEVEL <= cntr) AS SYS.odcinumberlist
)
)),
y AS
(SELECT ROWNUM seq, id2
FROM b
ORDER BY id2)
SELECT id1, flag, id2
FROM x, y
WHERE x.seq = y.seq
ORDER BY flag ;



Random Solutions  
 
programming4us programming4us