按日期列出的最佳结果为每个唯一项目的列

时间:2015-09-18 14:22:53

标签: sql sql-server tsql

我有一个按以下格式收集的数据表:

Title | Date       | Value
-----------------------
test1 | 2015-09-18 | 99
test1 | 2015-09-02 | 97
test1 | 2015-08-31 | 101
test1 | 2015-08-03 | 11
test1 | 2015-07-20 | 100
test2 | 2015-09-05 | 102
test2 | 2015-09-04 | 101
test2 | 2015-08-22 | 91
test2 | 2015-07-19 | 76
test2 | 2015-07-12 | 66

我希望能够在列中为每个不同的值输出最后结果。列标题(9月,8月,7月)顺便说一下并不重要。总会有3个月的时间。

Title | Sept | Aug | July
----------------------------
test1 | 99   | 101 | 100
test2 | 102  | 91  | 76

这可能吗?我已经考虑过CTE的使用,但是我对下一步感到有些困惑。

任何帮助/建议表示赞赏!

4 个答案:

答案 0 :(得分:1)

执行GROUP BY,使用CASE为每个所需月份执行条件MAX

select title,
       max(case when Month(Date) = 9 then value end),
       max(case when Month(Date) = 8 then value end),
       max(case when Month(Date) = 7 then value end)
from tablename
group by title

答案 1 :(得分:1)

您可以使用row_number将每个月的最后一个日期作为每个分区的第一行。

 select title, max(case when datepart(mm,datecol) = 9 then  value end) as sep,
              max(case when datepart(mm,datecol) = 8 then  value end) as aug,
              max(case when datepart(mm,datecol) = 7 then  value end) as jul
from (
      select *, 
      row_number() over(partition by title,datepart(mm,datecol) order by datecol desc) as rn
      from t1) t
where rn = 1
group by title;

Fiddle with sample data

答案 2 :(得分:1)

您可以使用CTE来帮助为实际的SELECT准备结果集。

$($("#tabs").find("li")[1]).hide();
$($("#tabs").find('#tab1')).hide();

见工作SQLFiddle

*注意:这只会占用每个“标题”的最后3个月的数据,但如果例如test1的最后一个月是9月,而test2的最后一个月是8月,那么它将是未对齐的。

答案 3 :(得分:0)

如果您想要过去三个月的数据轮转移:

select title,
       max(case when year(datecol) = year(getdate()) and month(datecol) = month(getdate()) - 2
                then value end) as months_2,
       max(case when year(datecol) = year(getdate()) and month(datecol) = month(getdate()) - 1
                then value end) as months_1,
       max(case when year(datecol) = year(getdate()) and month(datecol) = month(getdate())
                then value end) as months_0
from table t
group by title;

编辑:

哎呀,我不明白原来的问题。以下是修订后的代码:

select title,
       max(case when seqnum = 1 and year(datecol) = year(getdate()) and month(datecol) = month(getdate()) - 2
                then value end) as months_2,
       max(case when seqnum = 1 and year(datecol) = year(getdate()) and month(datecol) = month(getdate()) - 1
                then value end) as months_1,
       max(case when seqnum = 1 and year(datecol) = year(getdate()) and month(datecol) = month(getdate())
                then value end) as months_0
from (select t.*,
             row_number() over (partition by title, year(datecol), month(datecol)
                                order by datecol desc) as seqnum
      from table t
     ) t
group by title;

在这种情况下,max()并没有真正做任何事情,只是转动价值。