对列中具有相同数据的行进行SQL分组

时间:2018-08-13 15:25:24

标签: sql sql-server

我的数据如下:

MyData

同时创建5个数据点。我想将所有五个组合成一排。

我尝试使用以下查询:

SELECT 
    DateAndTime as Time, 
    (SELECT Val WHERE TagIndex = 0) as Normalized_Vac,
    (SELECT Val WHERE TagIndex = 1) as Avgerage_Vac,
    (SELECT Val WHERE TagIndex = 2) as RAL_ACT,
    (SELECT Val WHERE TagIndex = 3) as RAL_CMD,
    (SELECT Val WHERE TagIndex = 4) as PPH_weight
FROM 
    Line_32_floats
GROUP BY
    DateAndTime;

但是我得到了错误:

  

在选择列表中,'Line_32_floats.TagIndex'列无效,因为它既不包含在聚合函数中也不在GROUP BY子句中。

3 个答案:

答案 0 :(得分:2)

我建议条件聚合:

SELECT DateAndTime as Time, 
       MAX(CASE WHEN TagIndex = 0 THEN Val END) as Normalized_Vac,
       MAX(CASE WHEN TagIndex = 1 THEN Val END) as Avgerage_Vac,
       MAX(CASE WHEN TagIndex = 2 THEN Val END) as RAL_ACT,
       MAX(CASE WHEN TagIndex = 3 THEN Val END) as RAL_CMD,
       MAX(CASE WHEN TagIndex = 4 THEN Val END) as PPH_weight
FROM Line_32_floats f 
GROUP BY DateAndTime;

答案 1 :(得分:1)

您需要条件聚合:

SELECT DateAndTime, 
      MAX(CASE WHEN TagIndex = 0 THEN Val END),
       . . . 
FROM Line_32_floats
GROUP BY DateAndTime;

答案 2 :(得分:0)

这是我如何使用PIVOT的示例:

SELECT DateandTime, [0], [1], [2], [3], [4]
FROM 
(SELECT DateandTime, TagIndex, Val 
 FROM Line_32_floats WHERE DateandTime = '2018-08-09') as source_table
PIVOT
(
  MAX(Val)
  FOR TagIndex IN ([0], [1], [2], [3], [4])
) as pivot_table

您可以在此处访问有效的SQL提琴:http://sqlfiddle.com/#!18/2106c/3/0

由于您要排成一行,所以我假设您也在对列Val的不同值进行分组,在这种情况下,我将其视为MAX