将两个语句中的两列组合成单个结果集

时间:2014-10-14 18:12:52

标签: sql sql-server-2008

MS SQL Server 2008

我有两个SELECT语句

SELECT COUNT(*) as Number_of_SEP11_clients
FROM
...
WHERE 
...
and dbo.SEM_AGENT.AGENT_VERSION like '%11.%'



SELECT COUNT(*) as Number_of_SEP12_clients
FROM
...
WHERE 
...
and dbo.SEM_AGENT.AGENT_VERSION like '%12.%'

输出

Number_of_SEP11_clients
109111

Number_of_SEP12_clients
44812

如何制作输出

Number_of_SEP11_clients    Number_of_SEP12_clients
       109111                        44812

4 个答案:

答案 0 :(得分:1)

虽然您可以cross join来获得您想要的内容,但我猜测FROM和其他WHERE子句是相同的。在这种情况下,只需进行条件聚合:

SELECT SUM(CASE WHEN dbo.SEM_AGENT.AGENT_VERSION like '%11.%' THEN 1 ELSE 0 END) as Number_of_SEP11_clients,
       SUM(CASE WHEN dbo.SEM_AGENT.AGENT_VERSION like '%12.%' THEN 1 ELSE 0 END) as Number_of_SEP12_clients,

FROM
...
WHERE 
...

如果您愿意,可以添加:

WHERE . . . AND
      (dbo.SEM_AGENT.AGENT_VERSION like '%11.%' or dbo.SEM_AGENT.AGENT_VERSION like '%12.%')

答案 1 :(得分:1)

这可能取决于您的表结构,但您可以使用几个子查询来执行此操作:

SELECT (SELECT COUNT(*)
FROM
...
WHERE 
...
and dbo.SEM_AGENT.AGENT_VERSION like '%11.%') AS Number_of_SEP11,
(SELECT COUNT(*)
FROM
...
WHERE 
...
and dbo.SEM_AGENT.AGENT_VERSION like '%12.%') AS Number_of_SEP12;

答案 2 :(得分:1)

另一种选择..

SELECT Number_of_SEP11_clients, Number_of_SEP12_clients
FROM
(
    SELECT 1 as ID, COUNT(*) as Number_of_SEP11_clients
    FROM
    ...
    WHERE 
    ...
    and dbo.SEM_AGENT.AGENT_VERSION like '%11.%'
) SEP11CLIENT
INNER JOIN
(
    SELECT 1 as ID, COUNT(*) as Number_of_SEP12_clients
    FROM
    ...
    WHERE 
    ...
    and dbo.SEM_AGENT.AGENT_VERSION like '%12.%'
) SEPT12CLIENT
ON SEPT11CLIENT.ID = SEPT12CLIENT.ID

答案 3 :(得分:1)

试试这个:

SELECT (SELECT COUNT(*) AS Number_of_SEP11_clients
        FROM
        ...
        WHERE 
        ...
        and dbo.SEM_AGENT.AGENT_VERSION like '%11.%') AS Clients_SEP11,
        (SELECT COUNT(*) AS Number_of_SEP12_clients
        FROM
       ...
       WHERE 
       ...
       and dbo.SEM_AGENT.AGENT_VERSION like '%12.%') AS Clients_SEP12;