可以说,我有一个包含很多很多行像这样的表:
ID Range Range_begining Profit
----------------------------------------------------
1 (100-150) 100 -20
2 (200-250) 200 40.2
3 (100-150) 100 100
4 (450-500) 450 -90
...
我做这样一个简单的查询:
SELECT max([Range]) AS 'Range'
, count(ID) AS 'Count'
, round(avg([Profit]), 2) AS 'AVG Profit'
FROM
Orders
GROUP BY
Range_begining
该查询运行后,我得到这样的结果:
Range Count AVG Profit
------------------------------------
(100-150) 2 40
(200-250) 1 40.2
(450-500) 1 -90
...
非常简单 :)
我现在需要做的是用最小的和最大的利润,其中计数大于10大(这是一个参数)选择行
我能得到最小值与此:
SELECT TOP 1 [Range], [AVG Profit] FROM (
SELECT max([Range]) AS 'Range'
, count(ID) AS 'Count'
, round(avg([Profit]), 2) AS 'AVG Profit'
FROM
Orders
GROUP BY
Range_begining) X
WHERE
[Count]>10
ORDER BY
[AVG Profit] ASC --or DESC if I want max profit
我在想这样做的的UNION
上面的查询与ORDER BY DESC,但它不是最好的解决办法。
我需要做什么:
通过分组范围时,一个最小的,第二个最大AVG利润:选择2行。
编辑:如果我加2移动列到我的主数据表是这样的:
ID Range Range_begining Profit OrderDate Company
---------------------------------------------------------------------------------
1 (100-150) 100 -20 2012-01-02 1
2 (200-250) 200 40.2 2012-03-22 0
3 (100-150) 100 100 2012-02-05 0
4 (450-500) 450 -90 2012-05-12 1
...
然后尝试添加2个条件是这样的:
; with ordering as (
SELECT max([Range]) AS 'Range'
, count(ID) AS 'Count'
, round(avg([Profit]), 2) AS 'AVG Profit'
, row_number() over (order by avg([Profit])) rn_min
, row_number() over (order by avg([Profit]) desc) rn_max
FROM
Orders
GROUP BY
Range_begining
HAVING COUNT(ID) > 10
AND [Company]=@company
AND (@from= '' OR [OrderDate]>=@from)
AND (@to= '' OR [OrderDate]<=@to)
)
select [range], [count], [avg profit]
from ordering
where (rn_max = 1 or rn_min = 1)
我得到一个错误,因为[公司]和[订购日期]
因为它不是在聚合函数或GROUP BY子句是包含在HAVING子句中无效。
我怎样才能解决这个问题?
EDIT2得到它的工作!
; with ordering as (
SELECT max([Range]) AS 'Range'
, count(ID) AS 'Count'
, round(avg([Profit]), 2) AS 'AVG Profit'
, row_number() over (order by avg([Profit])) rn_min
, row_number() over (order by avg([Profit]) desc) rn_max
FROM
Orders
WHERE
[Company]=@company
AND (@from= '' OR [OrderDate]>=@from)
AND (@to= '' OR [OrderDate]<=@to)
GROUP BY
Range_begining
HAVING COUNT(ID) > 10
)
select [range], [count], [avg profit]
from ordering
where (rn_max = 1 or rn_min = 1)
编辑3我可以回到另一列有这样的描述:
Range AVG Profit Description
-------------------------------------------------
(200-250) 40.2 Max profit here
(450-500) -90 Min profit, well done
编辑4个快速答案(基于@NikolaMarkovinović答案):
; with ordering as (
SELECT max([Range]) AS 'Range'
, count(ID) AS 'Count'
, round(avg([Profit]), 2) AS 'AVG Profit'
, row_number() over (order by avg([Profit])) rn_min
, row_number() over (order by avg([Profit]) desc) rn_max
FROM
Orders
WHERE
[Company]=@company
AND (@from= '' OR [OrderDate]>=@from)
AND (@to= '' OR [OrderDate]<=@to)
GROUP BY
Range_begining
HAVING COUNT(ID) > 10
)
SELECT
CASE WHEN rn_max=1 THEN 'This is max' ELSE 'Min' END AS 'Description'
,[range]
,[count]
,[avg profit]
FROM ordering
WHERE (rn_max = 1 or rn_min = 1)