SQL:每个客户的最高订单中心

时间:2014-10-15 21:25:54

标签: sql sql-server max with-statement

我对SQL很新(大约两个月进入一个学习即用的位置),我正在尝试编写一个查询,为每个客户提供主要订单中心(即,哪个中心是每个客户最青睐)。我只希望每位客户一次退货。

现在,我有一个查询返回最高订购客户和相关中心。它看起来像这样:

with x as (
select
row_number() over (order by cusid asc)
as row
,cusid
,centerid
,count(centerid) numofcenter
from orderdb
where isnumeric (cusid)=1
and estimate=0
group by centered, cusid
)
select row, centered, cusid, numofcenter
from x
where numofcenter=(
select max(numofcenter) from x)
order by cusid

任何帮助或指导都会毫无疑问地受到赞赏。

2 个答案:

答案 0 :(得分:0)

未经测试,但这将是我要采用的基本概念:

WITH cte_centers AS
(SELECT DISTINCT cusid FROM orderdb)
SELECT cte_centers.cusid, x.numofcenter
FROM cte_centers 
CROSS APPLY
(SELECT TOP 1 
    count(centerid) numofcenter
 FROM orderdb
 WHERE isnumeric (cusid)=1
    AND estimate=0
    AND orderdb.cusid = cte_centers.cusid
 GROUP BY centered, cusid
 ORDER BY count(centerid) DESC
)x

答案 1 :(得分:0)

WITH CTE
AS (
    SELECT
        RANK() OVER (PARTITION BY cusid ORDER BY COUNT(centerid) DESC) AS row,
        cusid,
        centerid,
        COUNT(centerid) numofcenter
    FROM
        orderdb
    WHERE
        ISNUMERIC(cusid) = 1
        AND estimate = 0
    GROUP BY
        cusid,
        centerid)
SELECT
    row,
    cusid,
    centerid,
    numofcenter
FROM
    CTE
WHERE
    row = 1