如何获得我所拥有的SUM范围的MAX值?
当前输出:
Size | Format | ColB | Value
Large | PCT | Tmp1 | 23.05
Large | PCT | Tmp3 | 109.00
Large | PCT | Tmp50 | 3.22
Large | PCT | Tmp109 | 987.23
Large | PCT | Tmp58 | 455.30
预期产出:
Size | Format | ColB | Value | Max_Value
Large | PCT | Tmp1 | 23.05 | 987.23
Large | PCT | Tmp3 | 109.00 | 987.23
Large | PCT | Tmp50 | 3.22 | 987.23
Large | PCT | Tmp109 | 987.23 | 987.23
Large | PCT | Tmp58 | 455.30 | 987.23
如果可能,请告诉我。
目前的代码如下:
USE DB1
DECLARE @StartDate DATE
DECLARE @EndDate DATE
DECLARE @ColA VARCHAR(10)
DECLARE @ColB VARCHAR(20)
DECLARE @ColC VARCHAR(15)
DECLARE @ColD VARCHAR(15)
DECLARE @ColE VARCHAR(15)
DECLARE @ColF VARCHAR(15)
DECLARE @ColG VARCHAR(15)
BEGIN
SET @StartDate = '01/01/2017'
SET @EndDate = '01/14/2017'
SET @ColA = '%%'
SET @ColB = '%%'
SET @ColC = '%%'
SET @ColD = '%%'
SET @ColE = '%%'
SET @ColF = '%%'
SET @ColG = '%%'
END
SELECT
'Large' AS [Size]
,'PCT' AS [Format]
,[ColB]
,CAST((SUM([Numerator])/SUM([Denominator]))*100 AS NUMERIC(12,2)) AS [Value]
FROM [Table1] WITH(NOLOCK)
WHERE [Date] BETWEEN @StartDate AND @EndDate
AND [ColA] LIKE @ColA
AND [ColB] LIKE @ColB
AND [ColC] LIKE @ColC
AND [ColD] LIKE @ColD
AND [ColE] LIKE @ColE
AND [ColF] LIKE @ColF
AND [ColG] LIKE @ColG
GROUP BY [ColB]
提前谢谢。
答案 0 :(得分:1)
使用SUM
的子查询,然后使用MAX
功能获取此信息。
SELECT 'Large' AS [Size], 'PCT' AS [Format], [ColB],
CAST((SUM([Numerator])/SUM([Denominator]))*100 AS NUMERIC(12,2)) AS [Value],
(SELECT MAX(SUBValue)
FROM (SELECT [ColB], CAST((SUM([Numerator])/SUM([Denominator]))*100 AS NUMERIC(12,2)) AS [SUBValue]
FROM [Table1] WITH(NOLOCK)
WHERE [Date] BETWEEN @StartDate AND @EndDate
AND [ColA] LIKE @ColA
AND [ColB] LIKE @ColB
AND [ColC] LIKE @ColC
AND [ColD] LIKE @ColD
AND [ColE] LIKE @ColE
AND [ColF] LIKE @ColF
AND [ColG] LIKE @ColG
GROUP BY [ColB])) AS Max_Value
FROM [Table1] WITH(NOLOCK)
WHERE [Date] BETWEEN @StartDate AND @EndDate
AND [ColA] LIKE @ColA
AND [ColB] LIKE @ColB
AND [ColC] LIKE @ColC
AND [ColD] LIKE @ColD
AND [ColE] LIKE @ColE
AND [ColF] LIKE @ColF
AND [ColG] LIKE @ColG
GROUP BY [ColB]
答案 1 :(得分:0)
你可以使用这样的窗口函数:
SELECT
'Large' AS [Size]
,'PCT' AS [Format]
,[ColB]
,CAST((SUM([Numerator])/SUM([Denominator]))*100 AS NUMERIC(12,2)) AS [Value]
,cast(max(sum([Numerator])/sum([Denominator])) over(partition by null)) as numeric(12,2)) *100 as [MaxValue]
FROM [Table1] WITH(NOLOCK)
WHERE [Date] BETWEEN @StartDate AND @EndDate
AND [ColA] LIKE @ColA
AND [ColB] LIKE @ColB
AND [ColC] LIKE @ColC
AND [ColD] LIKE @ColD
AND [ColE] LIKE @ColE
AND [ColF] LIKE @ColF
AND [ColG] LIKE @ColG
GROUP BY [ColB]
我认为它适用于你的情况。