如何在查询中获取多个最大/最小值的时间值

时间:2013-03-03 08:47:57

标签: sql sql-server sql-server-2008 tsql

我的表包含以下值:
[quote_date],[TOTAL_TIME],[supA_demB],[demA_supB],[demB_supA],[supB_demA]

我想运行这样的查询:

SELECT quote_date
  ,min(demA_supB) as MinDemASupB
  ,max(demA_supB) as MaxDemASupB
  ,min(supA_demB) as MinSupADemB
  ,max(supA_demB) as MaxSupADemB
  ,min(demB_supA) as MinDemBSupA
  ,max(demB_supA) as MaxDemBSupA
  ,min(supB_demA) as MinSupBDemA
  ,max(supB_demA) as MaxSupBDemA
  FROM [dbo].[a_b_RatioTable]
  GROUP BY quote_date

有没有办法在此查询中为每个混合/最大值添加total_time值?
像:

SELECT quote_date
  ,min(demA_supB) as MinDemASupB
  ,something as MinDemASupBTime
  ,max(demA_supB) as MaxDemASupB
  ,something as MinDemASupBTime...

2 个答案:

答案 0 :(得分:1)

试试这个,

SELECT quote_date
  ,min(demA_supB) as MinDemASupB
  ,(select total_time from [dbo].[a_b_RatioTable] where quote_date = r.quote_date and demA_supB = min(r.demA_supB)) MinDemASupBTotal
  ,max(demA_supB) as MaxDemASupB
  ,(select total_time from [dbo].[a_b_RatioTable] where quote_date = r.quote_date and demA_supB = max(r.demA_supB)) MaxDemASupBTotal
  ,min(supA_demB) as MinSupADemB
  ,(select total_time from [dbo].[a_b_RatioTable] where quote_date = r.quote_date and supA_demB = min(r.supA_demB)) MinSupADemBTotal
  ,max(supA_demB) as MaxSupADemB
  ,(select total_time from [dbo].[a_b_RatioTable] where quote_date = r.quote_date and supA_demB = max(r.supA_demB)) MaxSupADemBTotal
  ,min(demB_supA) as MinDemBSupA
  .......
  ,max(demB_supA) as MaxDemBSupA
  ,min(supB_demA) as MinSupBDemA
  ,max(supB_demA) as MaxSupBDemA
  FROM [dbo].[a_b_RatioTable] r
  GROUP BY quote_date

注意:子查询可能会降低性能。

答案 1 :(得分:0)

只需将另一列添加为total_time即可。它会工作正常。

,min(demA_supB) as MinDemASupB
,max(demA_supB) as MaxDemASupB
,min(supA_demB) as MinSupADemB
,max(supA_demB) as MaxSupADemB
,min(demB_supA) as MinDemBSupA
,max(demB_supA) as MaxDemBSupA
,min(supB_demA) as MinSupBDemA
,max(supB_demA) as MaxSupBDemA
,total_time