3行作为一组SQL透视表(SQL Pivot table with 3 rows as a grou

2019-10-28 14:27发布

我使用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

Answer 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];

在线演示



Answer 2:

作为一个您以前的一个,在那里你需要统计不管共享相同值的顺序案件频跟进,我会解决这个问题。 前一个问题

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


文章来源: SQL Pivot table with 3 rows as a group
标签: sql pivot