无法在select语句中使用count()创建临时表

时间:2019-09-20 17:04:50

标签: sql sql-server temp

我正在尝试将这个select语句的输出放入临时表中。 select语句仅由字符串和聚合count()组成。这是我尝试使用的一些代码:

SELECT q.* into #tmpClientCounts
    from
    (
    SELECT 'Existing female clients in the program:',
    count([PER_SEX]) as Client_Count ---Count of female clients
    from #tmpClients c --- From another temp table
    -----
    -----bunch of sql that works fine
    -----
    union
    SELECT 'New female clients in the program:',
    count([PER_SEX]) as Client_Count
    from #tmpClients c
    -----
    -----bunch of sql that works fine
    -----
    ) as q

如您所见,我正在语句之间进行合并。这段代码产生如下所示的错误(部分错误):

No column name was specified for column 1 of 'q'.

An object or column name is missing or empty. For SELECT INTO statements, verify each column has a name

1 个答案:

答案 0 :(得分:0)

错误消息表明问题出在第一列,这只是一个常量字符串。试试:

SELECT q.* into #tmpClientCounts
    from
    (
    SELECT 'Existing female clients in the program:' as Header_col,
    count([PER_SEX]) as Client_Count ---Count of female clients
    from #tmpClients c --- From another temp table
    -----
    -----bunch of sql that works fine
    -----
    union
    SELECT 'New female clients in the program:'as Header_col,
    count([PER_SEX]) as Client_Count
    from #tmpClients c
    -----
    -----bunch of sql that works fine
    -----
    ) as q

请注意,问题不在于您的count([PER_SEX]) as Client_Count,而是第一列:'New female clients in the program:'