根据列组使用最小值和最大值查找创建全表视图

时间:2018-08-24 16:56:16

标签: sql sql-server tsql

我有一个表t1,其中有4列:

f1
f2
quant
rate

我需要创建一个视图,该视图包含t1中的所有记录,但列出最小和最大quant值以及每个rate和{{1 }}组。

我在下面有一个解决方案,但这似乎是一个很长的解决方法。在SQL Server 2014中,有没有更简单的方法来获得这些结果?

f1

4 个答案:

答案 0 :(得分:1)

我想窗口功能可以做到:

select
    f1, f2,
    quant,
    min(quant) over(partition by f1, f2) as min_quant,
    max(quant) over(partition by f1, f2) as max_quant,
    rate,
    min(rate) over(partition by f1, f2) as min_rate,
    max(rate) over(partition by f1, f2) as max_rate,
  from t1;

答案 1 :(得分:1)

您需要删除t1_min和t1_max并每次重新创建。

这是恕我直言的简单方法(但是您的要求含糊不清,例如,当存在多个min \ max值时会发生什么。无论如何,这至少与您的结果匹配)

SELECT f1, f2, quant, 
  min_quant, min_rate,
  max_quant, max_rate
FROM dbo.t1 t
CROSS APPLY (SELECT MIN(quant), MAX(quant) 
    FROM t1 tt WHERE t.f1=tt.f1 AND t.f2=tt.f2) tm(min_quant, max_quant)
CROSS APPLY (SELECT rate FROM t1 tt 
    WHERE t.f1=tt.f1 AND t.f2=tt.f2 AND tt.quant = tm.min_quant) tminr(min_rate)
CROSS APPLY (SELECT rate FROM t1 tt 
    WHERE t.f1=tt.f1 AND t.f2=tt.f2 AND tt.quant = tm.max_quant) tmaxr(max_rate);

答案 2 :(得分:1)

您可以在两个方向(升序和降序)上创建一个编号,并且在将编号的记录连接到t1时,从两个编号中都选择编号1:

WITH
  minmax (f1, f2, quant, rate, rn_min, rn_max) AS (
    SELECT f1, f2, quant, rate,
      ROW_NUMBER() OVER (PARTITION BY f1, f2 ORDER BY quant ASC),
      ROW_NUMBER() OVER (PARTITION BY f1, f2 ORDER BY quant DESC)
    FROM t1
  )
SELECT t1.f1, t1.f2, t1.quant, t1.rate,
  mi.quant AS min_quant, mi.rate AS min_rate,
  ma.quant AS max_quant, ma.rate AS max_rate
FROM t1
  INNER JOIN minmax mi ON t1.f1 = mi.f1 AND t1.f2 = mi.f2 AND mi.rn_min = 1
  INNER JOIN minmax ma ON t1.f1 = ma.f1 AND t1.f2 = ma.f2 AND ma.rn_max = 1

答案 3 :(得分:0)

从其他答案中得出好的线索,我发现Analytic Functions使用FIRST_VALUE()和LAST_VALUE()创建所需的输出。

Select
    f1
    ,f2
    ,quant
    ,MIN(quant) Over(Partition By f1, f2) As min_quant
    ,MAX(quant) Over(Partition By f1, f2) As max_quant
    ,rate
    ,FIRST_VALUE(rate) Over(Partition By f1, f2 Order By quant) As min_rate
    ,LAST_VALUE(rate) Over(Partition By f1, f2 Order By quant RANGE Between CURRENT ROW And UNBOUNDED FOLLOWING) As max_rate
From t1
Order By f1, f2, quant