2017-04-12 92 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