获得列的每个可能的组合

时间:2012-04-15 18:39:31

标签: sql sql-server sql-server-2008

如果我有一个刚刚返回的记录集:

SELECT * FROM USERS

    Name | Gender |   Company
    Bob  |  male  |  Abc Inc.
    Bob  |  male  |  Xyz Inc.
    Bob  |  male  |    NULL

我希望它能归还:

    Name | Gender |   Company
    NULL |  NULL  |    NULL
    NULL |  NULL  |    Abc Inc.
    NULL |  male  |    NULL
    NULL |  male  |    Abc Inc.
    NULL |  NULL  |    Xyz Inc.
    NULL |  male  |    Xyz Inc.
    Bob  |  NULL  |    NULL
    Bob  |  NULL  |    Abc Inc.
    Bob  |  male  |    NULL
    Bob  |  male  |    Abc Inc.
    Bob  |  NULL  |    Xyz Inc.
    Bob  |  male  |    Xyz Inc.

如何完成?

2 个答案:

答案 0 :(得分:1)

select Name, Gender, Company
from T
group by Name, Gender, Company with cube

答案 1 :(得分:0)

SELECT DISTINCT NAME, GENDER, COMPANY FROM TABLE
GROUP BY NAME, GENDER, COMPANY WITH CUBE