22,209
社区成员
发帖
与我相关
我的任务
分享
select companyid,year,market,max(sum(totalprice)) from t_order
where companyid is not null group by companyid,year,market
select companyid,market,year,max(sum) as max from
( select companyid,year,market,sum(totalprice) as sum from t_order
where companyid is not null group by companyid,year,market ) a
group by companyid, year,market
----------------------------------------------------------------
-- Author :DBA_HuangZJ(發糞塗牆)
-- Date :2014-08-19 14:57:09
-- Version:
-- Microsoft SQL Server 2012 - 11.0.5058.0 (X64)
-- May 14 2014 18:34:29
-- Copyright (c) Microsoft Corporation
-- Enterprise Edition: Core-based Licensing (64-bit) on Windows NT 6.3 <X64> (Build 9600: ) (Hypervisor)
--
----------------------------------------------------------------
--> 测试数据:[t_order]
if object_id('[t_order]') is not null drop table [t_order]
go
create table [t_order]([year] int,[market] varchar(4),[totalprice] int,[companyid] int)
insert [t_order]
select 1,'本地',6,6 union all
select 1,'本地',11,1 union all
select 1,'本地',16,2 union all
select 1,'本地',22,1 union all
select 1,'本地',26,4 union all
select 1,'本地',36,5 union all
select 2,'本地',5,2 union all
select 2,'本地',10,3 union all
select 2,'本地',15,1 union all
select 2,'本地',19,2 union all
select 2,'本地',20,3 union all
select 2,'本地',29,4 union all
select 2,'区域',9,1 union all
select 2,'区域',10,3 union all
select 2,'区域',15,4 union all
select 2,'区域',13,6 union all
select 2,'区域',14,5 union all
select 2,'区域',20,2
--------------开始查询--------------------------
;
WITH cte
AS ( SELECT companyid ,
year ,
market ,
SUM(totalprice) [sum]
FROM t_order
WHERE companyid IS NOT NULL
GROUP BY companyid ,
year ,
market
)
SELECT a.companyid ,
a.[year] ,
a.market ,
b.[max]
FROM cte a
INNER JOIN ( SELECT [year] ,
market ,
MAX([sum]) [max]
FROM cte
GROUP BY [year] ,
market
) b ON a.[year] = b.[year]
AND a.market = b.market AND a.sum=b.max
----------------结果----------------------------
/*
companyid year market max
----------- ----------- ------ -----------
2 2 区域 20
3 2 本地 30
5 1 本地 36
*/
WITH cte
AS ( SELECT companyid ,
year ,
market ,
SUM(totalprice) [sum]
FROM t_order
WHERE companyid IS NOT NULL
GROUP BY companyid ,
year ,
market
)
SELECT a.companyid ,
a.[year] ,
a.market ,
b.[max]
FROM cte a
INNER JOIN ( SELECT [year] ,
market ,
MAX([sum]) [max]
FROM cte
GROUP BY [year] ,
market
) b ON a.[year] = b.[year]
AND a.market = b.market
AND a.[sum] = b.[max]
...
) b ON a.[year] = b.[year]
AND a.market = b.market
AND a.[sum] = b.[max] -- 1楼少了这个条件
;
WITH cte
AS ( SELECT companyid ,
year ,
market ,
SUM(totalprice) [sum]
FROM t_order
WHERE companyid IS NOT NULL
GROUP BY companyid ,
year ,
market
)
SELECT a.companyid ,
a.[year] ,
a.market ,
b.[max]
FROM cte a
INNER JOIN ( SELECT [year] ,
market ,
MAX([sum]) [max]
FROM cte
GROUP BY [year] ,
market
) b ON a.[year] = b.[year]
AND a.market = b.market