如何在sql中选择最近12个月?

时间:2015-06-11 08:23:40

标签: sql sql-server select

我需要选择过去12个月。正如你在图片中看到的,可能会发生两次。 但我只希望它发生一次。它需要是最新的。 此外,该表应保留在此结构中,最新月份位于底部。

enter image description here

这是查询:

SELECT Monat2,
       Monat,
       CASE WHEN NPLAY_IND = '4P'
               THEN 'QuadruplePlay'
            WHEN NPLAY_IND = '3P'
               THEN 'TriplePlay'
            WHEN NPLAY_IND = '2P'
               THEN 'DoublePlay'
            WHEN NPLAY_IND = '1P'
               THEN 'SinglePlay'
       END AS Series,
       Anzahl as Cnt
FROM T_Play_n
where NPLAY_IND != '0P'
order by Series asc ,Monat

这是新查询

SELECT sub.Monat2,sub.Monat,
CASE WHEN NPLAY_IND = '4P'
    THEN 'QuadruplePlay'
     WHEN NPLAY_IND = '3P'
    THEN 'TriplePlay'
     WHEN NPLAY_IND = '2P'
    THEN 'DoublePlay'
    WHEN NPLAY_IND = '1P'
    THEN 'SinglePlay'
END
AS Series, Anzahl as Cnt FROM (SELECT ROW_NUMBER () OVER (PARTITION BY Monat2 ORDER BY Monat DESC)rn, 
                 Monat2,
                 Monat,
                 Anzahl,
                 NPLAY_IND
            FROM T_Play_n)sub
 where sub.rn = 1

它只显示一次月份,但并不是每个系列都这样做。 因此,每次播放都应该有12个月。

enter image description here

6 个答案:

答案 0 :(得分:3)

OracleSQL-Server中,您可以使用ROW_NUMBER

name =月份名称和num =月号:

  SELECT sub.name, sub.num
    FROM (SELECT ROW_NUMBER () OVER (PARTITION BY name ORDER BY num DESC) rn,
                 name,
                 num
            FROM tab) sub
   WHERE sub.rn = 1
ORDER BY num DESC;

答案 1 :(得分:1)

WITH R(N) AS
(
    SELECT 0
    UNION ALL
    SELECT N+1 
    FROM R
    WHERE N < 12
)

SELECT LEFT(DATENAME(MONTH,DATEADD(MONTH,-N,GETDATE())),3) AS [month]
FROM R

With R(N)是公用表表达式.R是您要生成的结果集(或表)的名称。 N是月份数。

答案 2 :(得分:0)

SQL Server中,您可以执行以下操作:

SELECT DateMonth, DateWithMonth -- Specify columns to select
FROM Tbl -- Source table
WHERE CAST(CAST(DateWithMonth AS INT) * 100 + 1 AS VARCHAR(20)) >= DATEADD(MONTH, -12,GETDATE()) -- Condition to return data for last 12 months
GROUP BY DateMonth, DateWithMonth -- Uniqueness
ORDER BY DateWithMonth -- Sorting to get latest records on the bottom

答案 3 :(得分:0)

所以听起来你想要选择包含最后几个月的行。这样的事情应该有效:

select * from [table_name]
where id in (select max(id) from [table_name] group by [month_column])

括号中的最后一个选项将获得每个月最后一次出现的id列表。如果您显示的年/月列已经不是降序,您可能希望最大化此列。

答案 4 :(得分:0)

你可以使用这样的东西(表dbo.Nums包含从0到11的int值)

SELECT DATEADD(MONTH, DATEDIFF(MONTH, '19991201', CURRENT_TIMESTAMP) + n - 12, '19991201'),
       DATENAME(MONTH,DateAdd(Month, DATEDIFF(month, '19991201', CURRENT_TIMESTAMP) + n - 12, '19991201'))
FROM dbo.Nums

答案 5 :(得分:0)

我建议使用group by作为月份名称,并使用max函数作为数字组件。如果不是数字,请使用to_number()