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

Can't create a temp table with count() in select statement

我正在尝试将此 select 语句的输出放入临时文件 table。 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

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

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:'