在SQL Server 2012

时间:2016-01-07 10:57:41

标签: sql-server

我想从count函数计算结果集的平均值。我使用了这个查询:

SELECT 
    CAST(AVG(purchase) AS NUMERIC (5,3))
FROM 
    (SELECT count(*) as purchase 
     FROM transactions
     GROUP BY payer_id) X

但我得到的结果是" 1"。我使用Excel来验证这个结果,它应该是1,635264484。

我还想返回count()列表和此列表的平均值,因此我重写了我的查询:

SELECT 
    tr1.payer_id, count(*) AS purchase
FROM 
    transactions AS tr1
GROUP BY 
    payer_id 

UNION ALL 

SELECT 'avg = ', AVG(X.purchase) 
FROM 
    (SELECT count(*) as purchase
     FROM transactions tr2
     GROUP BY tr2.payer_id) X

现在,查询运行一段时间,然后显示以下错误消息:

  

将数据类型varchar转换为数字时出错。

payer_id是数字(38,0)。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

您无法将'avg ='转换为由于您的UNION而尝试的数字,因为您的player_id是数字。

如果你将payer_id转换为文本,它应该有效:

SELECT 
    CAST(tr1.payer_id AS VARCHAR(255)), count(*) AS purchase
FROM 
    transactions AS tr1
GROUP BY 
    payer_id 

UNION ALL 

SELECT 'avg = ', AVG(X.purchase) 
FROM 
    (SELECT count(*) as purchase
     FROM transactions tr2
     GROUP BY tr2.payer_id) X