Sashko  Chehotsky
Sashko Chehotsky

Reputation: 408

Table field value to column (T-SQL)

I know, there are similar questions, but I can't understad it. I hope, you will help me to understand=) I have a 3 tables:

  1. Contact (int ID, nvarchar Name)
  2. City (int ID, nvarchar Name, int ContCount)
  3. Address (int ID, int CityID, int ContactID, int Year)

I need to make a table like this:

City | 2010 | 2011 | 2012 | 2013 |
 LA  |  201 |  231 |  198 |  211 |

Where 2010-2013 - values from Address.Year and {201, 231, 198, 211} are from City.ContCount Is in SQL some way to do it? If is, can you tell me about it=) I'll be really grateful) I'm novice in SQL, so even simple questions are hard to me)

Upvotes: 0

Views: 104

Answers (1)

David Garrison
David Garrison

Reputation: 2880

You are trying to create a two dimensional array in Sql, which is tricky. I know it isn't quite what you are asking, but the simplest solution is to do this with a group by like so

SELECT Year, City, Count(*)
FROM Address a
JOIN City c ON a.CityID = c.CityID
GROUP BY Year, City

which will give you

City, Year, Count
LA, 2010, 201
LA, 2011, 231
...

This will allow you to pivot on this data (In excel for example) to get what you need.

There is also a pivot option in T-SQL explained here

Upvotes: 1

Related Questions