0

我在 SQL 2005 中有一个要从中聚合数据的表,这是一个示例。

JobName       ProductionCounter       StartDate             EndDate               CounterName        Stage
----------------------------------------------------------------------------------------------------------

200           23                      2012-08-30 13:45:00                          Kilograms          Final
200           2                       2012-08-30 13:45:00                          Bars               Final
    [...]
200           46                      2012-08-30 13:45:00   2012-08-30 17:23:00    Kilograms          Final
200           4                       2012-08-30 13:45:00   2012-08-30 17:23:00    Bars               Final
300           20                      2012-08-30 13:45:00                          Kilograms          1st
300           10                      2012-08-30 18:12:00                          Bars               1st
    [...]
300           40                      2012-08-30 18:12:00   2012-08-30 19:17:00    Kilograms          1st
300           20                      2012-08-30 18:12:00   2012-08-30 19:17:00    Bars               1st

I want to format this into the following


JobName      TotalKilos       TotalBars       StartDate             EndDate               Stage
-----------------------------------------------------------------------------------------------

200          69               6               2012-08-30 13:45:00   2012-08-30 17:23:00   Final
300          60               30              2012-08-30 18:12:00   2012-08-30 19:17:00   1st

这让我意识到我对 SQL 一无所知。我已经尝试以下作为开始

SELECT JobName, SUM(KiloCounter)
FROM vwOeeInterval
GROUP BY JobName

SELECT JobName, SUM(BarCounter)
FROM vwOeeInterval
GROUP BY JobName

我的问题是:

  1. 如何将这些组合到一个查询中?

  2. 如何查询 StartDate 和 Stage 等列?特别是在工作完成之前没有填写结束日期?

任何指针将不胜感激。

4

2 回答 2

0

这是一个简单的聚合查询。您只需要添加所需的字段:

SELECT JobName, SUM(KiloCounter) as TotalKilos,
       sum(BarCounts) as TotalBars,
       min(StartDate) as StartDate,
       max(EndDate) as EndDate,
       max(Stage) as Stage 
FROM vwOeeInterval
GROUP BY JobName

我假设您知道 StartDate、EndDate 和 Stage 对于具有相同作业的所有行都是相同的或为 NULL。聚合将忽略 NULL 值。

于 2012-08-31T13:26:52.043 回答
0

当您尝试先根据Jobname然后根据countername获得总和时,您应该根据这 2 列进行分组。

不要忘记选择要分组的两列

样本看起来像这样 -
Select column1, column2, sum(column3) from tablename
where blah blah blah...
group by column1, column2

于 2012-08-31T13:50:06.867 回答