在SQL

时间:2018-09-17 21:07:25

标签: sql sql-server tsql

我有一个类似这样的数据:

Team    Month   Count_of_Stores
  a      4       10
  b      4        4
  c      4        6
  a      5        8
  b      5       14
  e      5        9
  a      6        7
  b      6        3
  f      6        1

我正在努力获得类似将行转换为列的输出:

团队月份数团队月份数团队月份数团队月份数 a 4 10 a 5 8 a 6 7 b 4 4 b 5 14 b 6 3 c 4 6 e 5 9 f 6 1

我确信在这里,pivot应该会很有帮助,但是在此处的适当用法上却感到困惑。任何帮助深表感谢。

1 个答案:

答案 0 :(得分:1)

我要根据提供的数据推断出团队联系。如下所示的内容可能对您有用(演示:http://rextester.com/GQHPV34978

CREATE TABLE temp
(
    [teamID] INT,
    [month] INT,
    [count_of_stores] INT
)

INSERT INTO temp
VALUES 
(1,4,10),
(2,4,4),
(3,4,6),
(1,5,8),
(2,5,14),
(3,5,9),
(1,6,7),
(2,6,3),
(3,6,1)

SELECT [teamID], 
    MAX(CASE WHEN MONTH = 4 THEN MONTH END )AS Month,
    MAX(CASE WHEN MONTH = 4 THEN count_of_stores END )  AS Count_of_Stores,
    MAX(CASE WHEN MONTH = 5 THEN MONTH END )AS Month,
    MAX(CASE WHEN MONTH = 5 THEN count_of_stores END )  AS Count_of_Stores ,
    MAX(CASE WHEN MONTH = 6 THEN MONTH END )AS Month,
    MAX(CASE WHEN MONTH = 6 THEN count_of_stores END )  AS Count_of_Stores 
FROM temp
GROUP BY teamID

根据新信息(演示:http://rextester.com/JIZQX61960)更新以下内容

create TABLE #temp
(
    [teamID] varchar,
    [month] INT,
    [count_of_stores] INT
)

INSERT INTO #temp
VALUES 
('a',4,10),
('b',4,4),
('c',4,6),
('a',5,8),
('b',5,14),
('e',5,9),
('a',6,7),
('b',6,3),
('f',6,1);


WITH monthGrouping AS
(
    SELECT row_number() over (partition by month order by month) as rn, [teamID], [month],[count_of_stores] FROM #temp
)

SELECT 
    MAX(CASE WHEN MONTH = 4 THEN [teamID] END )AS [teamID],
    MAX(CASE WHEN MONTH = 4 THEN MONTH END )AS Month,
    MAX(CASE WHEN MONTH = 4 THEN count_of_stores END )  AS Count_of_Stores,
    MAX(CASE WHEN MONTH = 5 THEN [teamID] END )AS [teamID],
    MAX(CASE WHEN MONTH = 5 THEN MONTH END )AS Month,
    MAX(CASE WHEN MONTH = 5 THEN count_of_stores END )  AS Count_of_Stores ,
    MAX(CASE WHEN MONTH = 6 THEN [teamID] END )AS [teamID],
    MAX(CASE WHEN MONTH = 6 THEN MONTH END )AS Month,
    MAX(CASE WHEN MONTH = 6 THEN count_of_stores END )  AS Count_of_Stores 
FROM monthGrouping
GROUP BY rn