Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2000 Forums
 SQL Server Development (2000)
 reverse crosstab type query thing

Author  Topic 

ts_abbott@hotmail.com
Starting Member

36 Posts

Posted - 2005-01-28 : 09:41:46
Hi, I've got this query to produce 2 rows like below:


Gender | Count
Male | 14
Female | 21

but they way I've done it seems really long winded (see below). Is there an easier way to do this?

[code]
SELECT 'Male' AS Name, z.Male AS Count FROM
(SELECT SUM(CASE WHEN c.Title='Mr' THEN 1 ELSE 0 END) AS Male
FROM LV_Customer c
INNER JOIN
(SELECT DISTINCT CustomerId FROM view_AllOrders
WHERE Status='Complete'
) a
ON c.Id=a.CustomerId) z

UNION

SELECT 'Female' AS Name, y.Female AS Count FROM
(SELECT SUM(CASE WHEN c.Title IN ('Mrs','Miss','Ms') THEN 1 ELSE 0 END) AS Female
FROM LV_Customer c
INNER JOIN
(SELECT DISTINCT CustomerId FROM view_AllOrders
WHERE Status='Complete'
) a
ON c.Id=a.CustomerId) y



Any suggestions as to how I could improve this would be much appreciated.

ts_abbott@hotmail.com
Starting Member

36 Posts

Posted - 2005-01-28 : 10:08:59
I'm gonna answer my own question as I've found an easier way to do it.


SELECT x.Gender, COALESCE(b.Num, 0) AS Num
FROM
(SELECT 'Male' AS Gender UNION SELECT 'Female' AS Gender UNION SELECT 'Unknown' AS Gender) x
LEFT OUTER JOIN
(SELECT y.Gender, COUNT(*) AS Num
FROM
(SELECT (CASE WHEN c.Title='Mr' THEN 'Male' WHEN c.Title IN ('Mrs','Miss','Ms') THEN 'Female' ELSE 'Unknown' END) AS Gender
FROM LV_Customer c
INNER JOIN
(SELECT DISTINCT CustomerId FROM view_AllOrders WHERE Status='Complete') z
ON c.Id=z.CustomerId) y
GROUP BY y.Gender) b
ON x.Gender=b.Gender

Go to Top of Page
   

- Advertisement -