当项目不按顺序时,多个SQL MAX

时间:2015-07-24 03:19:32

标签: sql sql-server tsql

我有一些数据如下:

DECLARE @MyTable AS TABLE 
(productName varchar(13), test1  int,test2  int)


INSERT INTO @MyTable
    (productName, test1,test2)
VALUES
    ('a', 1,1),
    ('a', 2,2),
    ('a', 3,3),
    ('b', 1,4),
    ('b', 2,5),
    ('b', 3,6),
    ('a', 1,7),
    ('a', 4,8),
    ('a', 5,9)
;
SELECT productname,MAX(test1) from @MyTable group BY productname

对test1列的MAX查询给出了

a,5 
b,3

但我需要将结果作为

a,3 
b,3 
a,5 

当我通过test2订购时

3 个答案:

答案 0 :(得分:2)

您可以通过使用row_numbers技巧解决此问题,以便分配2个不同的行号,一个用于整个数据,另一个用productname分区。如果比较这些数字之间的差异,您可以确定产品名称何时更改,并使用它来确定每个组的最大值。

select productname, max(test1) from (
SELECT *,
    row_number() over (order by test2 asc) -
    row_number() over (partition by productname order by test2 asc) as GRP 
from @MyTable
) X 
group by productname, GRP

您可以在SQL Fiddle

中对此进行测试

如果test2列始终是没有间隙的行号,则也可以使用它而不是第一行号列。如果您需要在数据中进行排序,则必须使用test1的最大值来执行此操作。

答案 1 :(得分:0)

请检查以下SQL Select语句

DECLARE @MyTable AS TABLE (productName varchar(13), test1  int,test2  int)

INSERT INTO @MyTable
    (productName, test1,test2)
VALUES
    ('a', 1,1),
    ('a', 2,2),
    ('a', 3,3),
    ('b', 1,4),
    ('b', 2,5),
    ('b', 3,6),
    ('a', 1,7),
    ('a', 4,8),
    ('a', 5,9)

DECLARE @MyTableNew AS TABLE (id int identity(1,1), productName varchar(13), test1  int,test2  int)
insert into @MyTableNew select * from @MyTable
--select * from @MyTableNew

;with cte as (
    SELECT
        id, productName, test1, test2,
        case when (lag(productName,1,'') over (order by id)) = productName then 0 else 1 end ischange
    from @MyTableNew
), cte2 as (
    select t.*,(select sum(ischange) from cte where id <= t.id) grp from cte t
)
select distinct grp, productName, max(test1) over (partition by grp) from cte2

这是根据以下SQL Server Lag() function tutorial实施的 Lag()函数用于识别和排序表数据中的组

答案 2 :(得分:-1)

请尝试此查询

DECLARE @MyTable AS TABLE 
(productName varchar(13), test1  int,test2  int)


INSERT INTO @MyTable
    (productName, test1,test2)
VALUES
    ('a', 1,1),
    ('a', 2,2),
    ('a', 3,3),
    ('b', 1,4),
    ('b', 2,5),
    ('b', 3,6),
    ('a', 1,7),
    ('a', 4,8),
    ('a', 5,9)
;
SELECT productname,MAX(test1) 
from @MyTable 
where test1 = test2
group BY productname
union all
SELECT productname,MAX(test1) 
from @MyTable 
where test1 != test2
group BY productname