2选择语句,1查询 - 返回2列

时间:2016-02-26 15:53:22

标签: sql-server select union

我有2个select语句,我想在1个查询中返回。我目前正在使用union,它在1个查询中返回两个结果,但它返回2行......

我希望尝试返回2列,而不是2行。

以下是我的询问:

SELECT distinct count([number]) AS 'Total' from [myTbl] WHERE [type] = 'online' union
SELECT distinct count([number]) AS 'Success' from [myTbl] WHERE [type] = 'online' and [MyValue] = 'true'

我想要2列.. TotalSuccess。这可能吗?也许不是通过union,而是通过其他一些方法?

5 个答案:

答案 0 :(得分:3)

您可以将其包装在两个子查询中,这样您将得到一行包含两个结果列。

SELECT
  (SELECT distinct count([number]) FROM [myTbl] WHERE [type]='online') AS Total,
  (SELECT distinct count([number]) FROM [myTbl] WHERE [type]='online' AND [MyValue]='true') AS Success

请注意,这里使用DISTINCT值得怀疑。

答案 1 :(得分:0)

这个怎么样?它将每行的值相加,设置为1表示成功,否则设置为0,因此计算成功。

SELECT  COUNT([number]) AS 'Total',
        SUM(CASE WHEN [MyValue] = 'true' THEN 1 ELSE 0 END) AS 'Success'
FROM    [myTbl]
WHERE   [type] = 'online'

答案 2 :(得分:0)

Common Table Expressions的完美用例。

;WITH CTE_Total AS (
    SELECT DISTINCT COUNT([number]) AS 'Total'
    FROM [myTbl]
    WHERE [type] = 'online'
), CTE_Success AS (
    SELECT DISTINCT COUNT([number]) AS 'Success'
    FROM [myTbl]
    WHERE [type] = 'online' and [MyValue] = 'true'
)
SELECT
    [Total] = CTE_Total.Total,
    [Success] = CTE_Success.Success;

答案 3 :(得分:0)

这很简单,就这样做:

SELECT Total, Success from 
(
    SELECT distinct count([number]) AS 'Total' from [myTbl] WHERE [type] = 'online' union
    SELECT distinct count([number]) AS 'Success' from [myTbl] WHERE [type] = 'online' and [MyValue] = 'true'
)

答案 4 :(得分:0)

试试这个

    SELECT 
       (SELECT count([number]) FROM [myTbl] WHERE [type] = 'online') AS 'Total',
       (SELECT count([number]) FROM [myTbl] WHERE [type] = 'online' and [MyValue] = 'true') AS 'Success'

或者更易于维护

    ;WITH tbl as (
        SELECT [number], [MyValue] FROM [myTbl] WHERE [type] = 'online'
    )
    SELECT 
       (SELECT count([number]) FROM tbl) AS 'Total',
       (SELECT count([number]) FROM tbl WHERE [MyValue] = 'true') AS 'Success'