Sql server SQL Server按日期进行选择和分组
我试图按产品分组,并根据datediff函数返回它们的平均使用时间 我的问题是:Sql server SQL Server按日期进行选择和分组,sql-server,sql-server-2012,Sql Server,Sql Server 2012,我试图按产品分组,并根据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.p
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 | 20
Product 2 | 3.5
Product 3 | 18
您可以使用子查询和平均
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
您可以使用子查询和平均
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
如果将
datediff()
从分组中删除,并将datediff()
包装在所选列的sum()
中,会发生什么情况?ie:sum(datediff())如果您从分组中删除datediff()
,并将datediff()
包装在所选列的sum()
中,会发生什么情况?ie:sum(datediff())几乎正确。只是错过了ABC.productNameCommon的组
几乎正确。只是缺少ABC.productNameCommon的组
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