join语句中的别名问题

时间:2011-06-02 07:53:19

标签: sql sql-server join alias

我遇到以下问题:

SELECT 
    g_contac.contid, g_contac.name, g_contac.email, f_sync.foreign_key,
    (
        SELECT COUNT(g_cpers.cpersid) 
        FROM g_cpers 
        WHERE g_cpers.contid = g_contac.contid
    ) AS employee_count
FROM f_sync 
    FULL OUTER JOIN g_contac ON 
    (
        g_contac.contid = f_sync.external_id AND 
        model = case when f_sync.employee_count = 0 then 'PRIVATE' else 'COMPANY' end
    )
WHERE model = 'COMPANY' or model = 'PRIVATE' OR model IS null

当我执行它时,我收到错误:

列名'employee_count'无效。

如何解决这个问题?

2 个答案:

答案 0 :(得分:5)

这是因为您在查询中提到了f_sync.employee_count,但f_sync没有名为employee_count的列:您只是在别名的查询中创建了一个动态列 employee_count

简单的解决方法是重复计算:

SELECT 
g_contac.contid, g_contac.name, g_contac.email, f_sync.foreign_key,
(
    SELECT COUNT(g_cpers.cpersid) 
    FROM g_cpers 
    WHERE g_cpers.contid = g_contac.contid
) AS employee_count
FROM f_sync 
FULL OUTER JOIN g_contac ON 
(
    g_contac.contid = f_sync.external_id AND 
    model = case when (SELECT COUNT(g_cpers.cpersid) 
    FROM g_cpers 
    WHERE g_cpers.contid = g_contac.contid) = 0 then 'PRIVATE' else 'COMPANY' end
)
WHERE model = 'COMPANY' or model = 'PRIVATE' OR model IS null;

更好的解决方法是创建一个包含此列的视图,这意味着它只能计算一次;

修改:改进了查询并合并了评论

您可以使用SQL not exists代替count(*) = 0来提高清晰度:

SELECT 
g_contac.contid, g_contac.name, g_contac.email, f_sync.foreign_key
FROM f_sync 
FULL OUTER JOIN g_contac ON 
(
    g_contac.contid = f_sync.external_id AND 
    model = case when not exists (SELECT * FROM g_cpers 
      WHERE g_cpers.contid = g_contac.contid) then 'PRIVATE' else 'COMPANY' end
)
WHERE model = 'COMPANY' or model = 'PRIVATE' OR model IS null;

答案 1 :(得分:0)

你能试试这个:

SELECT 
    gt.contid, gt.name, gt.email, f_sync.foreign_key,
    gt.employee_count
FROM f_sync 
    FULL OUTER JOIN
    (   SELECT
            g_contac.contid, g_contac.name, g_contac.email,
            (
                SELECT COUNT(g_cpers.cpersid) 
                FROM g_cpers 
                WHERE g_cpers.contid = g_contac.contid
            ) AS employee_count
        FROM g_contac  
    )  AS gt ON 
    (
        gt.contid = f_sync.external_id AND 
        model = case when gt.employee_count = 0 then 'PRIVATE' else 'COMPANY' end
    )