SQL Pivot表以3行为一组

时间:2017-08-04 00:21:22

标签: sql pivot

我正在使用SQL2012。我有以下SQL表,显示案例编号及其值。案例编号总是出现3个案例。你能帮我转动桌子吗?案件数量超过一千。

case  value
A     1992
A     1956
A     2007
B     2000
B     2001
B     1990
C     2000
C     1956
C     1817

预期结果:

Case  value1   value2   value3
A    1992      1956     2007
B    2000      2001     1990
C    2000      1956     1817

2 个答案:

答案 0 :(得分:1)

使用ROW_NUMBER并应用条件聚合:

WITH Cte AS(
    SELECT *,
        Rn = ROW_NUMBER() OVER(PARTITION BY [case] ORDER BY (SELECT NULL))
    FROM Tbl
)
SELECT
    [case],
    value1 = MAX(CASE WHEN Rn = 1 THEN value END),
    value2 = MAX(CASE WHEN Rn = 2 THEN value END),
    value3 = MAX(CASE WHEN Rn = 3 THEN value END)
FROM Cte
GROUP BY [case];

ONLINE DEMO

答案 1 :(得分:0)

我会将此问题作为对您之前的问题的跟进来解决,您需要计算无论顺序如何共享相同值的案例的频率。 Previous question

declare  @Table1 TABLE
    ([case] varchar(1), [value] int)
;

INSERT INTO @Table1
    ([case], [value])
VALUES
    ('A', 1992),    ('A', 1956),    ('A', 1986),
    ('B', 2000),    ('B', 2001),    ('B', 2003),
    ('C', 1986),    ('C', 1956),    ('C', 1992),
    ('D', 2005),    ('D', 2008),    ('D', 2002),
    ('E', 1954),    ('E', 1956),    ('E', 1992),
    ('G', 1954),    ('G', 1992) ,   ('G', 1956)


select min([case]) 'Case', min, mid, max,  count (*) frequency
from (
  select a.[case] [case], min(a.value) min, max(a.value) max, 
         sum(a.value)-min(a.value)-max(a.value) mid
  from @Table1 a      
  group by a.[case]) b
 group by min, mid, max
 order by min([case])

结果:

Case    min     mid     max     frequency
A       1956    1986    1992    2
B       2000    2001    2003    1
D       2002    2005    2008    1
E       1954    1956    1992    2

修改 如果您只需要4列没有频率,这就足够了:

 select a.[case] [Case], min(a.value) Value1, 
    sum(a.value)-min(a.value)-max(a.value) Value2,
    max(a.value) Value3         
  from @Table1 a      
  group by a.[case]

结果:

Case    Value1  Value2  Value3
A       1956    1986    1992
B       2000    2001    2003
C       1956    1986    1992
D       2002    2005    2008
E       1954    1956    1992
G       1954    1956    1992