简体   繁体   中英

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM