Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Joining Several results together in one table

Status
Not open for further replies.

Andy722

Programmer
Mar 24, 2008
2
GB
I have the following table.

File Type Date Opened
------------- ---------------
jpg 01-03-2010
gif 01-02-2010
png 18-02-2010
png 06-01-2010
jpg 02-03-2010
gif 25-02-2010
gif 30-01-2010
png 12-01-2010
jpg 19-02-2010

and would like to count all the different file types that were opened in January, February and March to produce this result.

File Type Opened in Jan Opened in Feb Opened in Mar
--------- ------------- ------------- -------------
jpg 0 1 2
gif 1 2 0
png 2 1 0

I have the following sql

SELECT [File Type], COUNT([File Type]) As [Opened in January] from Files
Where [Date Opened] between '01-01-2010' and '31-01-2010'
Group BY [File Type]

How do I extend my query to add a further two columns for Feb and March?
Also, How do I bring back the File Type when the Count is 0.
The above query does not bring back the jpg filetype but I still want all file types returned even if the count is 0.

I have trying left joins, sub queries etc but can't get my head around it.

Hope someone can help.
 
this is typically called a pivot query
Code:
SELECT "File Type"
     , COUNT(CASE WHEN EXTRACT(MONTH FROM "Date Opened") = 1
                  THEN 'curly' ELSE NULL END) AS January
     , COUNT(CASE WHEN EXTRACT(MONTH FROM "Date Opened") = 2
                  THEN 'larry' ELSE NULL END) AS February
     , COUNT(CASE WHEN EXTRACT(MONTH FROM "Date Opened") = 3
                  THEN 'moe'   ELSE NULL END) AS March
  FROM Files
GROUP
    BY "File Type"
that's the ANSI SQL solution (because that's the forum you posted in)

if the syntax doesn't work properly in your database system, you might have to tell us what it is

:)

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top