SQL Query按日期间隔查找数据

时间:2015-09-30 19:37:29

标签: sql sql-server-2008

我有一张带有雕像的桌子,如下所示:

Item     - Status - Date
12345    - 1 - 8/29/2015
12345    - 3 - 9/1/2015
12345    - 5 - 9/30/2015
22245    - 1 - 9/28/2015
22245    - 3 - 9/30/2015

我需要做的是查询返回以下内容:

Item - Status Today - Status 15 days ago - Status 30 days ago - Status 45 days ago
12345 -     5               5                    3                    1
22245 =     3               1                    1                    1

我无法弄清楚如何在查询中执行此操作。

时间间隔为15天,我需要知道当天每件物品的状态。

请帮忙......

2 个答案:

答案 0 :(得分:0)

这是SQL Fiddle或我认为你想要实现的目标。使用这样的查询。

WITH cte AS (
    SELECT  s.Item,
            s.STATUS,
            DATEDIFF(DAY, GETDATE(), [Date]) DaysAgo
    FROM    Statuses s
),
statusCte AS (
    SELECT 
        Item,
        MIN(CASE WHEN DaysAgo = 0 THEN [Status] END) [Status Today],
        MIN(CASE WHEN DaysAgo Between -15 AND -1 THEN [Status] END) [Status 15 days ago],
        MIN(CASE WHEN DaysAgo Between -30 AND -16 THEN [Status] END) [Status 30 days ago],
        MIN(CASE WHEN DaysAgo < -30 THEN [Status] END) [Status 45 days ago]
    FROM
        cte
    GROUP BY
        Item
)
SELECT  
    Item,
    COALESCE([Status Today], [Status 15 days ago], [Status 30 days ago], [Status 45 days ago]) [Status Today],
    COALESCE([Status 15 days ago], [Status 30 days ago], [Status 45 days ago], [Status Today]) [Status 15 days ago],
    COALESCE([Status 30 days ago], [Status 45 days ago], [Status 15 days ago], [Status Today]) [Status 30 days ago],
    COALESCE([Status 45 days ago], [Status 30 days ago], [Status 15 days ago], [Status Today] ) [Status 45 days ago]
FROM 
    statusCte

答案 1 :(得分:0)

这应符合您的期望:

SELECT item,
    [0] AS [Status today],
    [15] AS [Status 15 days ago],
    [30] AS [Status 30 days ago],
    [45] AS [Status 45 days ago]
FROM
(
  SELECT *,
   (SELECT TOP 1 t2.status FROM dbo.test1 t2 WHERE t2.item = z.item AND DATEDIFF(DAY,t2.date,GETDATE()) >= x.part ORDER BY date DESC) AS status
  FROM
    (SELECT DISTINCT t.item
     FROM dbo.test1 t) z
          CROSS JOIN
          (SELECT 0 AS part
          UNION SELECT 15
          UNION SELECT 30
          UNION SELECT 45) x ) sr
PIVOT
  (MAX(status) FOR part IN ([0],[15],[30],[45])) pvt