0

I have somehow joined up some tables and got some columns out so when I run SELECT SSN, Name, Year2010/Season1, Year2010/Season2, Year2010/Season3, Year2010/Season4 FROM (SELECT ...... ) AS WORKERS I get a table showen as below:

SSN  Name Year2010/Season1  Year2010/Season2  Year2010/Season3  Year2010/Season4
112  John         5.4  
234  Tom                          4.2
543  Ben                                                           9.3
234  Tom                                            3.2

The table is showing the workers and the hours they work at each year and period. However I am trying to combine those duplicate values (same person) and move all the hours into same row depending on the year and season. Something like this (where Tom is moved):

SSN  Name Year2010/Season1  Year2010/Season2  Year2010/Season3  Year2010/Season4
112  John         5.4                                
234  Tom                          4.2                3.2
543  Ben                                                           9.3

I have been trying for hours but don't really find a good way to combine these depending on the select statement I am doing to get this table. Any suggestion?

2 Answers 2

2

You want aggregation. You might be able to do this more simply by adjusting your query, but you can also do:

with q as (<your query here>)
select ssn, name,
       max([Year2010/Season1]) as  [Year2010/Season1],
       max([Year2010/Season2]) as  [Year2010/Season2],
       max([Year2010/Season3]) as  [Year2010/Season3],
       max([Year2010/Season4]) as  [Year2010/Season4]
from q
group by ssn, name;
Sign up to request clarification or add additional context in comments.

1 Comment

What happens if there are multiple rows for an employee with values during the same time period?
1

Seems like you need to use SUM:

SELECT  SSN,
        Name, 
        SUM([Year2010/Season1]) [Year2010/Season1],
        SUM([Year2010/Season2]) [Year2010/Season2],
        SUM([Year2010/Season3]) [Year2010/Season3],
        SUM([Year2010/Season4]) [Year2010/Season4]
FROM dbo.YourTable
GROUP BY SSN,
         Name;

2 Comments

Thanks for your respond. I forgot to mention the values of hours are set as VARCHAR. However I used this method and changed the SUM to MAX and it seems to work.
Is there any way to order the values by SSN?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.