具有未知列值的UNION ALL

时间:2014-06-11 16:01:21

标签: sql

您好我有一个使用UNION ALL的工作SELECT返回0值,但是我不知道如何将另一列添加到具有未知值的UNION:

SELECT status, type, company
    ROW_NUMBER() OVER (PARTITION BY title ORDER BY id) As RowNumber
FROM table
WHERE type IN ('type1', 'type2', 'type3') AND
    status IN ('status1', 'status2', 'status3')

/* issue starts here */
UNION ALL SELECT 'status1', 'type1', null, 1
UNION ALL SELECT 'status2', 'type1', null, 1
UNION ALL SELECT 'status3', 'type1', null, 1

/*                                    ^ unknown value */

/* ... repeat for all status * type combinations */

RowNumber用于查找父SELECT(未显示)中第一次出现的标题。

将预期的最终结果放在FROM子句中的另一个查询中以进行计数:

--------------------------------------
| status   | type  | company | count |
--------------------------------------
| status1  | type1 | abc     | 1     |
| status2  | type1 | abc     | 24    |
| status3  | type1 | abc     | 0     |
--------------------------------------

正如您所看到的,我在UNION ALL中为公司尝试了NULL,这是否有办法“使用”“公司”列中的值?

感谢。

2 个答案:

答案 0 :(得分:0)

我看到的第一件事是你的主选择返回四列,而联合会返回六列。所有union语句必须返回与初始select相同的列数。

如果要选择对用户唯一的公司,请执行实际选择:

UNION ALL
SELECT 'status1', 'type1', users_company, 1
from users_companies
where user = current_user

答案 1 :(得分:0)

我这可能是你正在寻找的东西

SELECT
    status
    , type
    , company
    , SUM(Counter) as count
FROM
(
    SELECT
        status
        , type
        , company
        ROW_NUMBER() OVER (PARTITION BY title ORDER BY id) As RowNumber
        , 1 AS Counter
    FROM table
    WHERE
        type IN ('type1', 'type2', 'type3')
        AND status IN ('status1', 'status2', 'status3')

    UNION ALL SELECT 'status1', 'type1', null, 1, 0
    UNION ALL SELECT 'status2', 'type1', null, 1, 0
    UNION ALL SELECT 'status3', 'type1', null, 1, 0
) t1
WHERE RowNumber = 1
相关问题