Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/sql-server-2008/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 2008 SQL重新格式化表列_Sql Server 2008_Sql Update_Reformat - Fatal编程技术网

Sql server 2008 SQL重新格式化表列

Sql server 2008 SQL重新格式化表列,sql-server-2008,sql-update,reformat,Sql Server 2008,Sql Update,Reformat,我现在有一张桌子,格式很不方便。 例子: 栏目: 这只是一个例子,实际上有5600列。 我想重新设置表格的格式,以便我刚才展示的示例更像: 有没有一种方法可以让我轻松地移动这些列,也许是基于对ID号的某种查找?我只需要将每个ID的所有数据放在一个单独列的记录中,而不是放在4个记录中,每个季度一个记录 谢谢 --到目前为止,我所做的只是创建一个具有不同ID的新表。然后我想使用某种连接或查找插入,可以将所有记录放入Q1中,其中quarter=1,dealer=dealer of record。我找

我现在有一张桌子,格式很不方便。 例子: 栏目:

这只是一个例子,实际上有5600列。 我想重新设置表格的格式,以便我刚才展示的示例更像:

有没有一种方法可以让我轻松地移动这些列,也许是基于对ID号的某种查找?我只需要将每个ID的所有数据放在一个单独列的记录中,而不是放在4个记录中,每个季度一个记录

谢谢


--到目前为止,我所做的只是创建一个具有不同ID的新表。然后我想使用某种连接或查找插入,可以将所有记录放入Q1中,其中quarter=1,dealer=dealer of record。

我找到了它。首先我做了一张新桌子

CREATE TABLE newtable (ID varchar (5), Q1 int, Q2 int, Q3 int, Q4 int)
然后我插入了不同的ID

INSERT INTO newtable
SELECT DISTINCT ID
FROM oldtable
然后,对于第1季度,我做了如下插入声明:

UPDATE newtable
SET newtable.Q1 = oldtable.sales
FROM newtable 
INNER JOIN oldtable
ON newtable.ID = oldtable.ID
WHERE oldtable.quarter = '1'
然后我只是复制并每个季度做一次,在WHERE语句中分别改为第二季度和第二季度

Select id, 
max(case when Quarter=1 then sales else null end) Q1,
max(case when Quarter=2 then sales else null end) Q2,
max(case when Quarter=3 then sales else null end) Q3,
max(case when Quarter=4 then sales else null end) Q4
from your_table_name
group by id;

只要确保检查重复项,我的实际数据集就有重复项,因为我使用了select distinct与另一列配对

您可以使用MySQL CASE语句

Select id, 
max(case when Quarter=1 then sales else null end) Q1,
max(case when Quarter=2 then sales else null end) Q2,
max(case when Quarter=3 then sales else null end) Q3,
max(case when Quarter=4 then sales else null end) Q4
from your_table_name
group by id;
Select id, 
max(case when Quarter=1 then sales else null end) Q1,
max(case when Quarter=2 then sales else null end) Q2,
max(case when Quarter=3 then sales else null end) Q3,
max(case when Quarter=4 then sales else null end) Q4
from your_table_name
group by id;