如何在一列中获得不止一列的行

时间:2019-02-12 13:18:32

标签: mysql database database-design unpivot

我要在一列中包含5列的行,并在该列中包含唯一行。

SELECT DISTINCT date,accept_date, question_date,success_date
FROM user_presentation;

我的行为:

date       accept_date question_date success_date
2018-12-07 2018-11-23  2018-12-21    2019-01-04
2018-12-21 2018-12-07  2019-01-04    2019-01-18
2019-01-04 2018-12-21  2019-01-18    2019-02-01
2019-01-18 2019-01-04  2019-02-01    2019-02-15
2019-02-01 2019-01-18  2019-02-15    2019-03-01

我希望一栏中的所有行都只有唯一值

2 个答案:

答案 0 :(得分:1)

SELECT DISTINCT val
  FROM 
     ( SELECT 'date' date_type 
            , date val
         FROM user_presentation
        UNION 
       SELECT 'accept_date' 
            , accept_date 
         FROM user_presentation
        UNION 
       SELECT 'question_date'
            , question_date  
         FROM user_presentation
        UNION 
       SELECT 'success_date'
            , success_date
         FROM user_presentation
     ) normalized;

答案 1 :(得分:0)

我不是100%地确定您想要什么,下面的示例将阐明这一点。如果@Strawberry处在正确的轨道上,那么它可以大大简化,因为UNION始终会删除重复项。

简化版本为:

SELECT date val FROM user_presentation
UNION 
SELECT accept_date FROM user_presentation
UNION 
SELECT question_date FROM user_presentation
UNION 
SELECT success_date FROM user_presentation