2017-04-12 44 views
0

我想按产品分组,并返回它们基于datediff函数使用的平均时间。SQL Server选择和分组由datediff

这里是我的查询:

SELECT products.productNameCommon, datediff(minute,history.timeOut, history.timeIn) as session 
FROM FlexLM_history history 
JOIN FlexLM_products products ON products.productID=history.productID 
where products.productType = 'base' and history.timeIn is Not NULL 
GROUP BY products.productNameCommon, datediff(minute,history.timeOut, history.timeIn) 
ORDER BY products.productNameCommon 

我的结果是这样的:

productNameCommon | avgSession 
----------------- | ---------- 
Product 1   | 5 
Product 1   | 15 
Product 1   | 40 
Product 2   | 2 
Product 2   | 5 
Product 3   | 12 
Product 3   | 24 

我真正需要的是这样的:

productNameCommon | avgSession 
----------------- | ---------- 
Product 1   | 20 
Product 2   | 3.5 
Product 3   | 18 
+0

如果从GROUP BY中删除'datediff()',并在列选择中将'datediff()'包装在'sum()'中,会发生什么?即:sum(datediff()) –

回答

1

你可以使用子查询和平均值

SELECT Q.ProductNameCommon, AvgSession = AVG(Session) FROM 
(--Your query 
    SELECT products.productNameCommon, datediff(minute,history.timeOut, history.timeIn) as Session 
    FROM FlexLM_history history 
    JOIN FlexLM_products products ON products.productID=history.productID 
    where products.productType = 'base' and history.timeIn is Not NULL 
    GROUP BY products.productNameCommon, datediff(minute,history.timeOut, history.timeIn) 
) as Q 
group by Q.ProductNameCommon 
order by Q.ProductNameCommon 
1
SELECT ABC.productNameCommon, AVG(Session) as avgSession 
FROM 
(
    SELECT products.productNameCommon, datediff(minute,history.timeOut, history.timeIn) as Session 
    FROM FlexLM_history history 
    JOIN FlexLM_products products ON products.productID=history.productID 
    where products.productType = 'base' and history.timeIn is Not NULL 
    GROUP BY products.productNameCommon, datediff(minute,history.timeOut, history.timeIn) 
) as ABC 
    GROUP BY ABC.productNameCommon --miss this line before 
    ORDER BY ABC.productNameCommon 
+0

几乎正确。只是缺少'GROUP BY ABC.productNameCommon' – ians

+0

@ians ahhh,谢谢xD – LONG