如何解决 group by, aggregate 的问题

how to get around problems with group by, aggregate

我有以下查询:

SELECT d.currentDate, t.ConfigId, t.value as value
FROM    #Dates AS d
        OUTER APPLY
        (   SELECT  t.value as value, t.FK_ShipDataSubsystemConfigId
            FROM    myTable AS t
            WHERE   t.[Timestamp] <= d.currentDate and t.ConfigId in (' + @IDList + ')
            and t.FK_DataSystemId <> 1
        ) AS t 
GROUP BY d.currentDate, t.ConfigId
)

其中 Dates 只是一个 table 保存了一堆我正在使用的日期时间,以确保我在我需要的时间间隔内获取数据。

我的问题出在 group by 子句上。查询无法正常工作,因为 value 不在 group by 或聚合函数中。我也尝试按 value 进行分组以使错误消失,但它只为我提供了我选择的时间间隔内的每个日期都与每个值相匹配——这不是我想要的。我最终应该得到一个 table,每对 date/ConfigId 对应一行。

当我从 select 中删除值并仅获取日期和 ConfigId 时,它工作正常。我得到了我应该得到的确切行数。

我从中提取的 table 看起来像这样:

PK_DataId    Timestamp        value     ConfigId
1            1/1/2015 12:00   234       5
2            1/1/2015 12:01   456       4

我期待得到这个:

Timestamp            value        ConfigId
1/1/2015 12:00:00    234          5
1/1/2015 12:00:00    456          4

我每十五分钟就有一个 configId/date 对的值。当我添加 max(value) 时,我每次只得到一个值,而不是不同的值。当我按值分组时,我得到数百万行,看起来我得到的每个时间戳都与任何其他时间戳中的每个值匹配。我真的不明白发生了什么。

如何在选择 value 的同时获得这些结果?

没有真实数据真的很难理解你的问题。

我猜你不想要这样的聚合函数。

SELECT d.currentDate, t.ConfigId, 
  MAX(t.value) as maxvalue, 
  MIN(t.value) as minvalue,
  COUNT(t.value) as totalvalue

所以我和你一起去寻找

simulating-group-concat-mysql-function-in-sql-server

ANDY   |  A100
ANDY   |  B391
ANDY   |  X010
TOM    |  A100
TOM    |  A510

returns:

ANDY   |  A100 / B391 / X010
TOM    |  A100 / A510

如果我没理解错的话,你只需要 top 1apply:

SELECT d.currentDate, t.ConfigId, t.value as value
FROM #Dates d OUTER APPLY
     (SELECT  TOP 1 t.value as value, t.FK_ShipDataSubsystemConfigId
      FROM    myTable AS t
      WHERE   t.[Timestamp] <= d.currentDate and
              t.ConfigId in (' + @IDList + ') and
              t.FK_DataSystemId <> 1
     ORDER BY t.[Timestamp] DESC
    ) t ;

编辑:

如果每个 config 和时间都需要一行:

SELECT d.currentDate, t.ConfigId, t.value as value
FROM #Dates d CROSS JOIN
     (SELECT DISTINCT FK_ShipDataSubsystemConfigId
      FROM myTable
      WHERE t.ConfigId in (' + @IDList + ')
     ) c OUTER APPLY
     (SELECT  TOP 1 t.value as value, t.FK_ShipDataSubsystemConfigId
      FROM    myTable AS t
      WHERE   t.[Timestamp] <= d.currentDate and
              t.ConfigId = c.FK_ShipDataSubsystemConfigId and
              t.FK_DataSystemId <> 1
      ORDER BY t.[Timestamp] DESC
     ) t ;

相同的基本思想,但这需要为所有配置生成所有行和 outer apply 之前的日期。