Link to home
Start Free TrialLog in
Avatar of andyw27
andyw27

asked on

Complex Query

Hello,

I need to construct a SQL 2008 table and associated query that can produce the following output
The table will contain a list of tasks; one of the fields will be a completion date.  When the query is run the query needs to be smart enough to work out the next 12 months from now and then populate the tasks to which month the completion date falls.  This in itself is quite complex, however to add a further layer of complexity it can’t be 1 row one date, all white spaces must be used.

Here is what the source table might look like

task_id      task      completion_date
1      Task 1      Mar
2      Task 2      May
3      Task 4      Mar
4      Task 5      Apr

For example instead of producing this:

Mar      Apr      May
Task 1              
       Task 5       
Task 4              
              Task 2

I need it to produce something like this:

Mar      Apr      May
Task 1      Task 5      Task 2
Task 4              
               
               

I have a completely free reign as to how the table can be structured in order to best achieve this outcome.
TIA
Avatar of ste5an
ste5an
Flag of Germany image

This should be better  done in the front-end. Otherwise:

DECLARE @Sample TABLE
    (
      task_id INT ,
      task NVARCHAR(255) ,
      completion_date NVARCHAR(255)
    );

INSERT  INTO @Sample
VALUES  ( 1, 'Task 1', 'Mar' ),
        ( 2, 'Task 2', 'May' ),
        ( 3, 'Task 4', 'Mar' ),
        ( 4, 'Task 5', 'Apr' );

WITH    Ordered
          AS ( SELECT   S.task ,
                        S.completion_date ,
                        ROW_NUMBER() OVER ( PARTITION BY S.completion_date ORDER BY S.task_id ) AS RN
               FROM     @Sample S
             )
    SELECT  P.Mar ,
            P.Apr ,
            P.May
    FROM    Ordered O PIVOT ( MAX(O.task) FOR O.completion_date IN ( Mar, Apr, May ) ) P;

Open in new window

Avatar of andyw27
andyw27

ASKER

Thanks I'll have a look.  I take it this is unable to cope with the dynamic elements, i.e. knowing what the next 12 months are, or displaying the months column even when there is no asscociated data, i.e. it should always display 12 columns
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
andyw27, do you still need help with this question?