提取数据2年并将数字转换为月份

时间:2014-12-18 10:35:16

标签: sql asp.net sql-server-2008

我有下表,月份和年份分开,我想加入创建日期(因为我没有这一天可以设置为第一个)

Measurement mm  yyyy
15000   1   2014
16000   2   2014
15000   5   2013
16000   3   2014
15000   4   2014
16000   5   2014
15000   6   2013
16000   7   2012

所以我希望输出为:

15000 01/01/2014
16000 01/02/2014

仅限过去两年。

这可能吗?

由于

1 个答案:

答案 0 :(得分:0)

SELECT Measurement,DT FROM
(
    SELECT Measurement,DENSE_RANK() OVER(ORDER BY YYYY DESC) RNK,
    CONVERT(varchar(11),'01'+'/'+CAST(MM AS VARCHAR(2))+'/'+CAST(YYYY AS VARCHAR(4)),103) DT
    FROM #TEMP
)TAB
WHERE RNK IN(1,2)

<强>更新

我正按照您的新要求进行更新

在这里,我们将获得所有月份和LEFT JOIN与您的表格

;WITH CTE1 AS
(
    SELECT 1 ID, CAST('01/01/2013' AS DATE) DT
    UNION ALL 
    SELECT ID+1,DATEADD(MONTH,1,DT) FROM CTE1
    WHERE ID<12
)
SELECT ID,DATENAME(MONTH,DT) [MONTH],TP.*,
DENSE_RANK() OVER(ORDER BY YYYY DESC) RNK
INTO #NEWTABLE
FROM CTE1
LEFT JOIN TEMP TP ON CAST(TP.MM AS NUMERIC(3,0)) = CAST(CTE1.ID AS NUMERIC(3,0)) 

现在我们声明2个变量,第一个变量用于获取值以显示月份行作为列,第二个变量用于替换NULL with zero

DECLARE @cols NVARCHAR (MAX)
DECLARE @NullToZeroCols NVARCHAR (MAX)

SELECT @cols = COALESCE (@cols + ',[' + [MONTH] + ']', 
              '[' + [MONTH] + ']')
               FROM    (SELECT DISTINCT ID,[MONTH] FROM #NEWTABLE) PV  
               ORDER BY ID

SET @NullToZeroCols = SUBSTRING((SELECT ',ISNULL(['+[MONTH]+'],0) AS ['+[MONTH]+']' 
FROM(SELECT DISTINCT [MONTH],ID FROM #NEWTABLE GROUP BY [MONTH],ID)TAB  
ORDER BY ID  FOR XML PATH('')),2,8000)

现在我们选择表格中的最后两年并将其转动

DECLARE @query NVARCHAR(MAX)
SET @query = 'SELECT yyyy,' + @NullToZeroCols + ' FROM 
             (
                 SELECT yyyy, [MONTH], Measurement FROM #NEWTABLE
                 WHERE RNK IN(1,2)
             ) x
             PIVOT 
             (
                 SUM(Measurement)
                 FOR [MONTH] IN (' + @cols + ')
              ) p
              WHERE yyyy IS NOT NULL
              ORDER BY yyyy;' 

EXEC SP_EXECUTESQL @query