如何解决“参数数据类型varchar对于格式函数的参数1无效”。在mssql中

时间:2019-04-16 17:39:03

标签: sql sql-server format

来自学校的你好,我正在查询。现在,我进行了一次查询,获得了以下中的评分:非常差,不足,足够和非常好。现在,我使用以下代码来计算每个类别在评分中所占的百分比:

SELECT format(klasse, count(klasse) * 100 / (
            SELECT count(*)
            FROM (
                SELECT year(boekingsdatum) AS jaar
                    ,iif(rating IS NULL, 'Geen rating', iif(rating <= 3, 'Zwaar onvoldoende', iif(rating <= 5, 'Onvoldoende', iif(rating < 8, 'Voldoende', 'Zeer goed')))) AS Klasse
                FROM boeking b
                ) AS percentage
            ), 'p')
FROM (
    SELECT year(boekingsdatum) AS jaar
        ,iif(rating IS NULL, 'Geen rating', iif(rating <= 3, 'Zwaar onvoldoende', iif(rating <= 5, 'Onvoldoende', iif(rating < 8, 'Voldoende', 'Zeer goed')))) AS Klasse
    FROM boeking b
    ) AS b
GROUP BY klasse

现在,如果不使用该格式执行此查询,它将给出正确的数字而没有%符号。但格式显示标题中的错误

1 个答案:

答案 0 :(得分:1)

试图了解您要做什么,我相信这就是您想要的。

SELECT klasse, format( count(klasse)*1. / (SELECT count(*)FROM boeking), 'p')
FROM (
    SELECT CASE WHEN rating IS NULL THEN 'Geen rating'
                WHEN rating <= 3 THEN 'Zwaar onvoldoende'
                WHEN rating <= 5 THEN 'Onvoldoende'
                WHEN rating < 8 THEN 'Voldoende'
                ELSE 'Zeer goed' END AS Klasse
    FROM boeking b
    ) AS b
GROUP BY klasse

我必须留下一个非常重要的说明。 FORMAT将使此查询比在前端格式化它慢得多。如果需要在此处进行格式化(忽略将来将该列用作数字),则可以使用以下格式。

SELECT klasse, CAST( CAST( count(klasse)*100. / (SELECT count(*)FROM boeking) AS decimal(10,2)) AS varchar(13)) + '%'
FROM (
    SELECT CASE WHEN rating IS NULL THEN 'Geen rating'
                WHEN rating <= 3 THEN 'Zwaar onvoldoende'
                WHEN rating <= 5 THEN 'Onvoldoende'
                WHEN rating < 8 THEN 'Voldoende'
                ELSE 'Zeer goed' END AS Klasse
    FROM boeking b
    ) AS b
GROUP BY klasse