错误:操作数数据类型nvarchar对于求和运算符无效

时间:2019-02-09 01:07:09

标签: sql sql-server

该错误发生在我尝试SUM(genre) AS "Total"的第5行上。

我尝试将convert设置为genre的{​​{1}}或将int设置为cast,都导致操作错误。

int

1 个答案:

答案 0 :(得分:1)

如果您想要所有类型的合计,请使用窗口函数:

SELECT CAST(genre AS CHAR(20)) AS Genre,
       COUNT(*) as cnt,
       SUM(COUNT(*)) OVER () as total
FROM title_genre
GROUP BY genre
ORDER BY "Count" DESC;

对于比例,您将使用:

(COUNT(*) * 1.0 / SUM(COUNT(*)) OVER ()) as proportion