1 行到 1 列的数据透视表

问题描述 投票:0回答:1

我有一个查询,使用以下查询输出 7 天内的每日传送带启动时间:

Select 
    format(min(case when location = 0 and scantime between getdate()-1 and getdate() then scantime end),'hh:mm:ss:tt') [StartTime1]
    ,format(min(case when location = 0 and scantime between getdate()-2 and getdate()-1 then scantime end),'hh:mm:ss:tt') [StartTime2]
    ,format(min(case when location = 0 and scantime between getdate()-3 and getdate()-2 then scantime end),'hh:mm:ss:tt') [StartTime3]
    ,format(min(case when location = 0 and scantime between getdate()-4 and getdate()-3 then scantime end),'hh:mm:ss:tt') [StartTime4]
    ,format(min(case when location = 0 and scantime between getdate()-5 and getdate()-4 then scantime end),'hh:mm:ss:tt') [StartTime5]
    ,format(min(case when location = 0 and scantime between getdate()-6 and getdate()-5 then scantime end),'hh:mm:ss:tt') [StartTime6]
    ,format(min(case when location = 0 and scantime between getdate()-7 and getdate()-6 then scantime end),'hh:mm:ss:tt') [StartTime7]
    
  FROM [BaldorFoods_WcsDb].[dbo].[ScanLog]
  where datepart(hour,scantime) in (18,19,20,21,22,23,0,1,2,3,4,5,6)

这会输出图像中的表格:MyTable。我将如何更改此表,以便将行名称标记为 StartTime1、StartTime2、StartTime3.... 等。

我尝试使用数据透视表函数,但在指定函数的输入时遇到困难。

sql sql-server pivot
1个回答
0
投票

我会采取不同的方法

select format(scantime, 'hh:mm:ss:tt')
from (values
  (0),
  (1),
  (2),
  (3),
  (4),
  (5),
  (6)
) as up(n)
cross apply (
  select top(1) scantime
  from [BaldorFoods_WcsDb].[dbo].[ScanLog]
  where datepart(hour,scantime) in (18,19,20,21,22,23,0,1,2,3,4,5,6)
    and scantime between getdate() - up.n and getdate() - (up.n-1)
  order by scantime
) as d;

为了解释,我们来分解一下。这是一个更简单的版本,只为您提供日期边界:

select n, getdate() - up.n, getdate() - (up.n-1)
from (values
  (0),
  (1),
  (2),
  (3),
  (4),
  (5),
  (6)
) as up(n)

从那里,我们使用

cross apply
获取第一行(按扫描时间列排序),该行位于给定的一组日期边界内,并且还应用了小时部分的谓词。

© www.soinside.com 2019 - 2024. All rights reserved.