SQL - 每组不同表中项的最大值

时间:2013-11-30 12:47:51

标签: sql sql-server

我有以下SQL表,包含以下数据:

site-obj-Prices

id  Parameter   Value   ActionFunc  ActionValue ChainTo ChainOperator   GroupID
1   Locality    0       Set         6           NULL        NULL        1
2   Locality    1       Set         3           NULL        NULL        2
3   Locality    0       Set         15          4           AND         3
4   State       61      Set         15          NULL        NULL        3
5   Locality    0       Set         18          6           AND         4
6   State       61      Set         18          7           AND         4
7   AreaCode    954     Set         18          NULL        NULL        4
8   Locality    0       Add         -1          9           AND         5
9   State       61      Add         -1          10          AND         5
10  AreaCode    954     Add         -1          11          AND         5
11  Supplier    242     Add         -1          NULL        NULL        5
12  Weight      3       Add         3           NULL        NULL        6
13  Weight      3       Add         2           14          AND         7
14  Supplier    242     Add         2           NULL        NULL        7

site-obj-PricesParams

id  Parameter   Order
1   Locality    0
2   State       1
3   AreaCode    2
4   Weight      3
5   Supplier    4

在以下查询中,我需要更改ActionLevel,以便它反映

MAX(Order) from [site-obj-PricesParams] 

表示每个GroupID中的所有参数。

因此,如果我有一个参数'Locality'和'Weight'的组,ActionLevel应为3。

任何帮助将不胜感激。

SELECT 
   id, Parameter, Value, ActionFunc, ActionValue, ChainTo, ChainOperator, GroupID, 
   COUNT(GroupID) OVER(PARTITION BY GroupID) AS ActionLevel
FROM 
   [site-obj-Prices] as Actions
WHERE
   GroupID NOT IN (SELECT [GroupID]
                   FROM [site-obj-Prices] as act
                   INNER JOIN @ParametersList as par ON act.Parameter = par.sKey 
                                                     AND act.Value <> par.sValue
                   UNION 
                   SELECT [GroupID]
                   FROM [site-obj-Prices] as act
                   LEFT JOIN @ParametersList as par ON act.Parameter = par.sKey 
                   WHERE par.sKey IS NULL
                  )
ORDER BY 
   ActionLevel ASC

1 个答案:

答案 0 :(得分:2)

如果我理解你的要求没有错,那么希望这会有用。

SELECT id,Parameter,Value,ActionFunc,ActionValue,ChainTo,
ChainOperator,GroupID, MAX([Order]) OVER(PARTITION BY GroupID) AS ActionLevel
FROM [site-obj-Prices] as Actions
Inner Join [site-obj-PricesParams] as Params 
On Actions.Parameter = Params.Parameter
Where GroupID NOT IN (
            SELECT [GroupID]
            FROM [site-obj-Prices] as act
            INNER JOIN @ParametersList as par
                ON act.Parameter=par.sKey AND act.Value<>par.sValue
            UNION 
            SELECT [GroupID]
            FROM [site-obj-Prices] as act
            LEFT JOIN @ParametersList as par
                ON act.Parameter=par.sKey WHERE par.sKey IS NULL
    )
    ORDER BY ActionLevel ASC