简体   繁体   English

表字段值到列(T-SQL)

[英]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: 希望您能帮助我理解=)我有3个表:

  1. Contact (int ID, nvarchar Name) 联系人(int ID, nvarchar Name)
  2. City (int ID, nvarchar Name, int ContCount) 城市(int ID, nvarchar Name, int ContCount)
  3. Address (int ID, int CityID, int ContactID, int Year) 地址(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? 在2010-2013年Address.Year和{ City.ContCount }中的值来自City.ContCount SQL中的某种方式吗? 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) 如果是,您能告诉我吗=)我将非常感激)我是SQL的新手,所以即使是简单的问题也很难解决)

You are trying to create a two dimensional array in Sql, which is tricky. 您试图在Sql中创建一个二维数组,这很棘手。 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. 这将使您能够利用这些数据(例如在excel中)来获取所需的数据。

There is also a pivot option in T-SQL explained here T-SQL中还有一个枢轴选项,在这里说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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