SQL将基于日期行的数据比较到

时间:2017-09-13 17:34:20

标签: sql sql-server date compare multiple-columns

我是SQL的新手,我有一个这样的SQL表

Name | Date                | performance_reading_1 | performance_reading_2     
---------------------------------------------------------------------------
BOB   2016-11-05 21:59:59     2000.000                 398776.000
JON   2016-11-05 23:59:59     2120.000                 118273.000
BOB   2016-11-06 13:59:59     3450.000                 228666.000
JON   2016-11-06 09:22:59     2432.000                 158643.000
BOB   2016-12-09 13:59:59     3450.000                 228666.000
JON   2016-12-11 09:22:59     2432.000                 158643.000

基本上我需要一个sql语句,它将在1行2个不同的日期显示每个日期的性能数据。

2个日期和名称将有所不同,并在变量中传递。 我需要在$ date1和$ date2

上说出Name $ name
Name | Date 1                | perf_1   | perf_2    | Date 2                  | perf_1   | perf_2
----------------------------------------------------------------------------------------------------------------
BOB   2016-11-05 21:59:59     2000.000    398776.000   2016-12-09 13:59:59     3450.000    228666.000

1 个答案:

答案 0 :(得分:2)

自我加入在这里运作良好:

DECLARE @Name varchar(50) = 'Bob'
DECLARE @Date1 datetime = '2016-11-05 21:59:59'
DECLARE @Date2 datetime = '2016-12-09 13:59:59'

SELECT T.Name,
       T.Date as 'Date1',
       T.Performance_Reading_1 as 'perf_1',
       T.Performance_Reading_2 as 'perf_2',
       T2.Date as 'Date2',
       T2.Performance_Reading_1 as 'perf_1',
       T2.Performance_Reading_2 as 'perf_2',
FROM YourTable T
INNER JOIN YourTable T2 on T.Name = T2.Name
WHERE T.Name = @Name
AND T.Date = @Date1
AND T2.Date = @Date2

PS每个Performance_Reading的每个表的别名都相同,可能会让人感到困惑。