如何查询sql以获取最新记录日期值

时间:2019-07-11 06:06:40

标签: sql-server tsql pivot

我具有以下结构

username, date,      value,       IDexam,   No.Points
--------------------------
brad,     1/2/2010,  not pass       exam1   10
brad,     2/2/2010,  pass           exam1   15
brad,     1/3/2010,  pass           exam2   20
brad,     1/3/2010,  not pass       exam3   12

fred,     1/3/2010,  pass           exam2   25
fred,     5/3/2010,  pass           exam2   20
fred,     5/4/2010,  not pass       exam3   12

etc..

我想要的是:

username,  Exam1-value,  Exam1-date, Exam1-points, Exam2-value,  Exam2-date, Exam2-points, Exam3-value, Exam3-date, Exam3-points
--------------------------
brad,     pass, 2/2/2010   15,   pass, 1/3/2010,  20, , ,
fred,     , , , pass, 5/3/2010   20,   not pass, 5/4/2010,  12

因此,对于同一IDExam的多个记录,以获取同一用户的最新记录,但在列上 预先感谢

1 个答案:

答案 0 :(得分:2)

尝试一下:

CREATE TABLE #DataSource
(
    [username] VARCHAR(16)
   ,[date] DATE
   ,[value] VARCHAR(16)
   ,[IDexam] VARCHAR(16)
   ,[No.Points] TINYINT
);


INSERT INTO #DataSource ([username], [date], [value], [IDexam], [No.Points])
VALUES ('brad', '1/2/2010', 'not pass', 'exam1', 10)
      ,('brad', '2/2/2010', 'pass', 'exam1', 15)
      ,('brad', '1/3/2010', 'pass', 'exam2', 20)
      ,('brad', '1/3/2010', 'not pass', 'exam3', 12)
      ,('fred', '1/3/2010', 'pass', 'exam2', 25)
      ,('fred', '5/3/2010', 'pass', 'exam2', 20)
      ,('fred', '5/4/2010', 'not pass', 'exam3', 12);

SELECT [username]
      ,MAX(IIF([IDexam] = 'exam1', [date], NULL)) AS [Exam1-value]
      ,MAX(IIF([IDexam] = 'exam1', [value], NULL)) AS [Exam1-date]
      ,MAX(IIF([IDexam] = 'exam1', [No.Points], NULL)) AS [Exam1-points]
      ,MAX(IIF([IDexam] = 'exam2', [date], NULL)) AS [Exam2-value]
      ,MAX(IIF([IDexam] = 'exam2', [value], NULL)) AS [Exam2-date]
      ,MAX(IIF([IDexam] = 'exam2', [No.Points], NULL)) AS [Exam2-points]
      ,MAX(IIF([IDexam] = 'exam3', [date], NULL)) AS [Exam3-value]
      ,MAX(IIF([IDexam] = 'exam3', [value], NULL)) AS [Exam3-date]
      ,MAX(IIF([IDexam] = 'exam3', [No.Points], NULL)) AS [Exam3-points]
      ,MAX(IIF([IDexam] = 'exam4', [date], NULL)) AS [Exam4-value]
      ,MAX(IIF([IDexam] = 'exam4', [value], NULL)) AS [Exam4-date]
      ,MAX(IIF([IDexam] = 'exam4', [No.Points], NULL)) AS [Exam4-points]
      ,MAX(IIF([IDexam] = 'exam5', [date], NULL)) AS [Exam5-value]
      ,MAX(IIF([IDexam] = 'exam5', [value], NULL)) AS [Exam5-date]
      ,MAX(IIF([IDexam] = 'exam5', [No.Points], NULL)) AS [Exam5-points]
FROM 
(
    SELECT *
          ,ROW_NUMBER() OVER (PARTITION BY [username], [IDexam] ORDER BY [date] DESC) AS [RowID]
    FROM #DataSource
) DS
WHERE [RowID] = 1
GROUP BY [username]

DROP TABLE #DataSource;

enter image description here