从单个列中透视多个相同的列

时间:2019-12-03 22:32:23

标签: sql sql-server

在这里我放入示例数据。这是我的SQL表,我想将CardNo作为列标题。Value1和Value2作为CardNo的数据。

SQL Table Screenshot

这是我在Excel中创建的示例输出,用于问题发布,但我想通过SQL查询获得这些结果。

Actual I want output in this manner

我正在尝试进行SQL查询,但没有获得所需的实际输出。

2 个答案:

答案 0 :(得分:0)

使用条件聚合:

select
    date,
    cardno,
    max(case when SignalType = 4 then Value1 end) Value1_4,
    max(case when SignalType = 4 then Value2 end) Value2_4,
    max(case when SignalType = 5 then Value1 end) Value1_5,
    max(case when SignalType = 5 then Value2 end) Value2_5,
    max(case when SignalType = 6 then Value1 end) Value1_6,
    max(case when SignalType = 6 then Value2 end) Value2_6
from mytable
group by date, cardno

注意:它没有显示在预期的结果中,但是很可能您希望date出现在group by子句中。我添加了。

答案 1 :(得分:0)

使用PIVOT。

SELECT
 [Date],
 [CardNo],
 CASE WHEN [4] IS NOT NULL THEN [Value1] END AS [4],
 [4],
 CASE WHEN [5] IS NOT NULL THEN [Value1] END AS [5],
 [5],
 CASE WHEN [6] IS NOT NULL THEN [Value1] END AS [6],
 [6]
FROM
(
  SELECT
  [Date], [CardNo], [Value1],
  [SignalType], [Value2]
  FROM YourTable
  WHERE [SignalType] IN (4, 5, 6)  --  Optional. Just for efficiency reasons. By only retrieving what's required.
) Src
PIVOT
(
  MAX([Value2])
  FOR [SignalType] IN ([4], [5], [6])
) Pvt
ORDER BY
 [Date],
 [CardNo],
 [Value1];