sql-server:尝试添加参数的列名无效

时间:2014-06-10 16:29:32

标签: sql sql-server

我有这个查询,并尝试在我的表Hospital_1的{​​{1}}列下添加_ MainHospital时的参数。我在Survey内收到了“无效的列名'MainHospital'”。一切都来自同一个表'调查',该列存在。

有关更多背景信息,请参阅此处的上一个问题:sql server: Creating a ranked list by assigning weights

WHERE MainHospital = @MainHospital

我不能回答我自己的问题,但我明白了。刚为每个子查询添加了where子句。

    declare @MainHospital varchar(50)='Hospital_1';
         SELECT a.categories, 
        ISNULL(b.count_1,0) + ISNULL(c.count_2,0) + ISNULL(d.count_3,0) + ISNULL(e.count_4,0) +     ISNULL(f.count_5,0) AS total_score FROM

        (SELECT DISTINCT Growth1 AS categories FROM [DBNAME].[schema].[TABLENAME]
        UNION SELECT DISTINCT Growth2 AS categories FROM [DBNAME].[schema].[TABLENAME]
        UNION SELECT DISTINCT  Growth3 AS categories FROM [DBNAME].[schema].[TABLENAME]
    UNION SELECT DISTINCT  Growth4 AS categories FROM [DBNAME].[schema].[TABLENAME]
    UNION SELECT DISTINCT  Growth5 AS categories FROM [DBNAME].[schema].[TABLENAME]) AS a

    LEFT JOIN
    (SELECT Growth1, COUNT(Growth1) * 5 AS count_1
    FROM  [DBNAME].[schema].[TABLENAME]
    GROUP BY Growth1) AS b
    ON a.categories = b.Growth1

    LEFT JOIN
    (SELECT Growth2, COUNT(Growth2) * 4  AS count_2
    FROM  [DBNAME].[schema].[TABLENAME]
    GROUP BY Growth2) AS c
    ON a.categories = c.Growth2

    LEFT JOIN
    (SELECT Growth3, COUNT(Growth3) * 3  AS count_3
    FROM  [DBNAME].[schema].[TABLENAME]
    GROUP BY Growth3) AS d
    ON a.categories = d.Growth3

    LEFT JOIN
    (SELECT Growth4, COUNT(Growth4) * 2  AS count_4
    FROM  [DBNAME].[schema].[TABLENAME]
    GROUP BY Growth4) AS e
    ON a.categories = e.Growth4

    LEFT JOIN
    (SELECT Growth5, COUNT(Growth5) * 1  AS count_5
    FROM  [DBNAME].[schema].[TABLENAME]
    GROUP BY Growth5) AS f
    ON a.categories = f.Growth5

    WHERE MainHospital = @MainHospital
    ORDER BY total_score DESC

1 个答案:

答案 0 :(得分:0)

我将WHERE MainHospital = @MainHospital放在每个连接子查询中。

LEFT JOIN
    (SELECT Growth1, COUNT(Growth1) * 4 AS count_1
    FROM  Survey
    WHERE MainHospital = @MainHospital
    GROUP BY Growth1) AS b
    ON a.categories = b.Growth1