2016-08-30 29 views
2

对不起,如果我以错误的方式提问,我是SQL新手。TSQL:需要有新列而不是下一行

我有我在哪里参加不同的表

然后后插入值一个临时表时,我看到,我需要更新临时表与3场(colm1的日期时间,colm2日期时间,colm3钱) 来到为此,我在临时表中创建了字段。

现在,

select colm1,colm2,sum(colm3) 
    from OrginalTable 
    where [email protected] 
    group by colm1,colm2 

让想这给人造成这样的:

enter image description here

这里更新到临时表后,如果有多个数据,那么我需要做类似下面,直到15倍:

Colm1,Com2,Colm3,colm1,colm2,colm3,

,而不是创建新行我需要这在1行显示为新的领域与

enter image description here

执行结果应该是所有为1行。

我真的很困惑,我是否可以做预期的事情,如果有办法请有人给我举例或解决这个问题。

最后,感谢您的帮助

+1

对不起,这太混乱了,你可以给我看一下wh在你想要的结果? '如果有多个数据,那么我需要像下面这样做,直到15次< - 这是什么意思?,为什么15次? – Lamak

+0

如果你想要新的列,我相信你将不得不选择它们。 –

+0

@Lamak我已经更新了期望的问题,谢谢 – Akka

回答

1

你可以使用UNPIVOT然后Dynamic PIVOT

DEMO

设置:

create table temp (
    col1 integer, col2 integer, col3 integer 
) 

insert into temp values (1, 1, 1000); 
insert into temp values (1, 2, 500); 
insert into temp values (2, 3, 800); 
insert into temp values (2, 4, 700); 
insert into temp values (3, 1, 1100); 

UNPIVOT查询:您需要一个row_number来创建一个虚假的列名称。但随后覆盖行1给大家,让所有列出现在单行

WITH cte as (
    SELECT row_number() over (order by col1, col2) as rn, 
      col1, col2, col3 
    FROM temp 
) 
SELECT 1 as rn, 
     'c_' + 
     CAST(rn AS VARCHAR(16)) + '_' + 
     myCol as myCol, 
     myVal 
INTO temp2    
FROM 
    (SELECT rn, col1, col2, col3 
    FROM cte) p 
UNPIVOT 
    (myVal FOR myCol IN 
     (col1, col2, col3) 
)AS unpvt; 

SELECT * FROM temp2; 

动态透视

DECLARE @cols AS NVARCHAR(MAX), 
    @query AS NVARCHAR(MAX); 

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.myCol) 
      FROM temp2 c 
      FOR XML PATH(''), TYPE 
      ).value('.', 'NVARCHAR(MAX)') 
     ,1,1,'') 

set @query = 'SELECT rn, ' + @cols + ' from 
      (
       select rn 
        , myCol 
        , myVal 
       from temp2 
      ) x 
      pivot 
      (
       max(myVal) 
       for myCol in (' + @cols + ') 
      ) p ';      

EXEC sp_executesql @query 

输出:逆透视和动态透视结果

enter image description here

1

听起来你应该为你的数据库UI层没有做到。

否则,你需要像

SELECT t1.*, t2.*, ....... , t15.* 
FROM yourTable as t1, 
     yourTable as t2, 
     ...... 
     yourTable as t15 
WHERE t1.col1 >= t2.col1 and t1.col2 > t2.col2 
    AND t2.col1 >= t3.col1 and t2.col2 > t3.col2 
    .... 
    AND t14.col1 >= t14.col15 and t14.col2 > t15.col2 

问题是你需要知道的有15行,所以如果这个数字缩小查询不会工作。

这就是为什么你应该这样做的UI,而不是

+0

不,这是通过SQL独自完成的。希望我可以通过UI做到,但如果是这样,我必须制作一个UI – Akka