我在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
我的问题是:
如何将这些组合成一个查询?
如何查询StartDate和Stage等列?特别是结束日期 在作业完成之前没有填写?
任何指针都会非常感激。
答案 0 :(得分: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值。
答案 1 :(得分:0)
当您尝试首先根据作业名然后反对获取总和时,您应该根据这两列进行分组。
请勿忘记选择
样本看起来像这样 -
Select column1, column2, sum(column3) from tablename
where blah blah blah...
group by column1, column2