I have a table that looks like this:
DECLARE @myTable TABLE (SampleID varchar(max), site varchar(max), SPDate date)
INSERT @myTable
SELECT 'A-1', 1, '9/1/2012' UNION ALL
SELECT 'A-2', 1, '10/1/2012' UNION ALL
SELECT 'A-3', 1, '10/15/2012' UNION ALL
SELECT 'A-5', 1, '5/1/2012' UNION ALL
SELECT 'A-4', 1, '1/1/2012' UNION ALL
SELECT 'B-1', 2, '11/1/2012' UNION ALL
SELECT 'B-2', 2, '8/1/2012' UNION ALL
SELECT 'B-3', 2, '5/1/2012' UNION ALL
SELECT 'B-4', 2, '4/1/2012' UNION ALL
SELECT 'C-1', 3, '10/1/2012' UNION ALL
SELECT 'C-2', 3, '10/15/2012' UNION ALL
SELECT 'C-3', 3, '7/1/2012' ;
What I would like to have is a query that gives me all the dates that are > 75 days from today and then sorted in descending order (e.g. the most recent date first).
So for my table, the output would look like this:
Site1 Site2 Site3
A-1 B-2 C-2
A-5 B-3 C-3
A-4 B-4
So I know how I can make the Site1, Site2 and Site3 queries separate like this
SELECT SampleID FROM @myTable
WHERE DATEDIFF(DAY, SPDate, GETDATE()) > 75 AND
site=1 ORDER BY SPDate DESC
How do I make these three queries into one table ?
Thanks !
You can easily perform this using the
PIVOTfunction. If you have only the 3sitevalues that you show above, then you can hard-code the values, similar to this:See SQL Fiddle with Demo
But is you have an unknown number of sites, then you can implement a dynamic sql version of this:
See SQL Fiddle with Demo
Both generate the same result: