sql嵌套选择无效列

时间:2010-10-14 21:31:32

标签: sql sql-server database sql-server-2005

嘿所有,     我现在一直在努力选择一个声明,我希望得到一些帮助。我目前在临时表中有一个列表IP,我想计算这个IP充当服务器的次数以及它充当客户端的次数。无论我如何操纵这个select语句,我都会得到相同的错误,告诉我ServerCount是一个无效的列,无论我用什么替换null。这是select语句:

select IPS, sum (ClientCount) as ClientCount, sum(ServerCount) as ServerCount
from (
       select IP as IPS, Count(*) as ClientCount, null
       from table1 join temp_table 
       on table1.client_ip = temp_table.IP
       group by IP
       union all
       select null,IP as IPS, Count(*) as ServerCount
       from table1 join temp_table 
       on table.server_ip = temp_table.IP
       group by IP
       )t
group by IPS, ClientCount, ServerCount

上半场和下半场在没有工会的情况下独立工作。有关导致此错误的原因的任何想法?此外,如果我使用Nulls,我也会得到第二个错误。以下是包含空值的完整错误:

Msg 8155,Level 16,State 2,Line 1 没有为't'的第3列指定列。 Msg 207,Level 16,State 1,Line 13 列名称“ServerCount”无效。 Msg 207,Level 16,State 1,Line 1 列名称'ServerCount'无效。

感谢。

4 个答案:

答案 0 :(得分:3)

您需要在union的第一个查询中定义servercount。 Aslo null可能没有意义....我会用零而不是。

select IPS, sum (ClientCount) as ClientCount, sum(ServerCount) as ServerCount
from (
       select IP as IPS, Count(*) as ClientCount, 0 as serverCount
       from table1 join temp_table 
       on table1.client_ip = temp_table.IP
       group by IP
       union all
       select IP as IPS,0 as ClientCount, Count(*) as ServerCount
       from table1 join temp_table 
       on table.server_ip = temp_table.IP
       group by IP
       )t
group by IPS, ClientCount, ServerCount

答案 1 :(得分:0)

子查询中的第一个SELECT需要定义所有列名,因此您需要更改:

select IP as IPS, Count(*) as ClientCount, null

select IP as IPS, Count(*) as ClientCount, null AS ServerCount

另外,我会更改子查询中的第二个SELECT,以便以相同的顺序给出列:

select IP as IPS, null AS ClientCount, Count(*) as ServerCount

答案 2 :(得分:0)

您的查询无效:

select
    IPS,
    sum(ClientCount) as ClientCount,
    sum(ServerCount) as ServerCount
from (
    select
        IP as IPS,
        Count(*) as ClientCount,
        null as ServerCount
    from table1 join temp_table 
    on table1.client_ip = temp_table.IP
    group by IP

    union all

    select
        null,
        IP as IPS,
        Count(*)
    from table1 join temp_table 
    on table.server_ip = temp_table.IP
    group by IP
)t
group by IPS, ClientCount, ServerCount

当你有一个联合时,他们从第一个查询中获得列别名。您的第一个查询需要指定ServerCount列名称

答案 3 :(得分:0)

执行UNION ALL时,列的顺序应相同。查询通常会将第一个SELECT语句的名称作为列的名称。

另外,在外部查询中,我不确定为什么要按聚合列进行分组;我认为这不会起作用。我认为你想要的东西可能更好地服务于:

SELECT tt.IP,
       (SELECT COUNT(*) FROM table1 t1 WHERE tt.IP = t1.client_ip) AS ClientCount,
       (SELECT COUNT(*) FROM table1 t2 WHERE tt.IP = t2.server_ip) AS ServerCount
FROM   temp_table tt
ORDER BY tt.IP

至少看起来简单得多。