结果集的AVG

时间:2018-09-21 12:45:51

标签: sql-server

早上好。 SQL新手在这里寻求帮助。我正在尝试从子查询中获取结果集的AVG。子查询可以正常工作,并为我提供所需的结果集,但我无法使结果集的AVG正常工作。任何指导将不胜感激。

SELECT AVG(COUNT) FROM   
(SELECT COUNT(DISTINCT(table2.item_no))   
FROM table1   
JOIN table2 ON table1.order_numb = table2.order_numb
WHERE user_so = 'paul'
AND order_date BETWEEN '9/20/2017'AND '9/20/2018'
GROUP BY table1.order_numb);

这里是我自己试图从子查询中得到的结果集的一个样本,然后我尝试转而得到以下AVG:

216
181
163
156
144
144
143
133
129
129
120
114
113
112
112
109
108
104
103
99
98
98
98
98
98
97
97
97
96
96
94
94
94
93
93

1 个答案:

答案 0 :(得分:2)

我认为您想要这样的东西:

SELECT AVG(a_number) FROM   
(SELECT COUNT(DISTINCT(table2.item_no)) AS a_number  
FROM table1   
JOIN table2 ON table1.order_numb = table2.order_numb
WHERE user_so = 'paul'
AND order_date BETWEEN '9/20/2017'AND '9/20/2018'
GROUP BY table1.order_numb) AS the_subquery

我没有相同的数据表,所以这是一个简化的示例:

SELECT AVG(a_number) FROM (
SELECT 100 AS a_number
UNION
SELECT 200 AS a_number
UNION
SELECT 300 AS a_number
UNION
SELECT 400 AS a_number
) AS the_subquery

您似乎缺少需要为子查询加上别名,并且想AVG为子查询中返回的值的别名。

更新

根据评论,如果您希望答案四舍五入到小数点后两位,则需要CAST更改为其他数据类型,如下所示:

SELECT ROUND(AVG(CAST(a_number AS FLOAT)), 2) FROM   
(SELECT COUNT(DISTINCT(table2.item_no)) AS a_number  
FROM table1   
JOIN table2 ON table1.order_numb = table2.order_numb
WHERE user_so = 'paul'
AND order_date BETWEEN '9/20/2017'AND '9/20/2018'
GROUP BY table1.order_numb) AS the_subquery

或其他无法访问该表的人

SELECT ROUND(AVG(CAST(a_number AS FLOAT)), 2) FROM (
SELECT 100 AS a_number
UNION
SELECT 200 AS a_number
UNION
SELECT 300 AS a_number
UNION
SELECT 403 AS a_number
) AS the_subquery

您可以在此处详细了解ROUNDAVGCAST的工作方式:How do I retrieve decimals when rounding an average in SQL