SQL根据另一列

时间:2018-05-08 20:06:28

标签: sql select pivot where multiple-columns

使用以下数据集:

Extender_Record_ID: 1, 1, 2, 2, 3, 3, 4, 4, 5, 5
Field_ID: 100, 101, 100, 101, 100, 101, 100, 101, 100, 101
Date: 1/1/2018, 1/2/2018, 1/14/2018, 1/15/2018, 2/1/2018, 2/3/2018, 
      2/15/2018, 2/17/2018, 3/2/2018, 3/5/2018

我想获得输出:

Start Date: 1/1/2018, 1/14/2018, 2/1/2018, 2/15/2018, 3/2/2018  
End Date: 1/2/2018, 1/15/2018, 2/3/2018, 2/17/2018, 3/5/2018

我正在尝试根据ID列中的值将日期列拆分为两个单独的日期列。我想将其插入更大的查询中。

对不起,我是新来的。非常感谢任何帮助!

3 个答案:

答案 0 :(得分:0)

它就像一个永远是min而另一个是max一样简单,你可以做到:

SELECT MIN(DATE) AS Date1
     , MAX(DATE) AS Date2
  FROM ...
GROUP BY ID

或许可能是一个更复杂的枢轴,但我们可能需要知道那个

的SQL风格

答案 1 :(得分:0)

select extendedrecordid, field_id, max(case when field_id = 1 then date else null end )date1,
max(case when field_id = 2 then date else null end )date2
from yourtable group by extendedrecordid, field_id

答案 2 :(得分:0)

根据您的评论I got the min and max query to produce what i needed for the minor example.,您可能真正需要的是:

SELECT 
CASE WHEN Id = 1 THEN [DateField] END AS Date1, 
CASE WHEN Id = 2 THEN [DateField] END AS Date2
FROM [MyTable]