繁体   English   中英

MS Access 2010 SQL排名前三的销售额

[英]MS Access 2010 SQL Top 3 Sales in Group by

我有一个表格,包括年份,季度,团队和价格。 它显示了团队的每一笔销售。 我们在公司有10个团队。 我想知道每年的每个季度,哪三支球队的销量最高。 那么我被困在哪里? 此时,我将每个团队每季度的总销售额进行分组。 仍然缺少o只能获得销量最高的三支最佳球队。 我到目前为止得到了这个:

SELECT 
    a1.year,
    a1.quarter,
    a1.team,
    sum(a1.price) as Total

FROM
    tbl_sales a1    

inner JOIN
    tbl_sales a2 
        ON a1.year = a2.year
            and a1.quarter = a2.quarter
            and a1.team = a2.team
            and a1.price = a2.price
     where
           some restrictions here
GROUP BY
    a1.year,
    a1.quarter,
    a1.team

有些东西告诉我,我很接近,只有一个带有top函数的子查询会有所帮助,但我无法弄明白。 任何帮助非常感谢:)非常感谢!

在MS Access中,您可以使用INTOP执行此操作:

select s.*
from tbl_sales as s
where s.team in (select top (3) s2.team
                 from tbl_sales as s2
                 where s2.year = s.year and s2.quarter = s.quarter
                 order by s2.price desc
                );

您可能需要向外部查询和内部查询添加限制,具体取决于它们的含义。

尝试:

SELECT TOP 3
    a1.year,
    a1.quarter,
    a1.team,
    sum(a1.price) as Total

FROM
    tbl_sales a1    

inner JOIN
    tbl_sales a2 
        ON a1.year = a2.year
            and a1.quarter = a2.quarter
            and a1.team = a2.team
            and a1.price = a2.price
     where
           some restrictions here
GROUP BY
    a1.year,
    a1.quarter,
    a1.team

ORDER BY 
    sum(a1.price) DESC

编辑,尝试以下内容,您可能需要其他条件以确保获得正确的结果集,但这应该返回where子句中指定的每个季度的前3位,我不知道您为什么使用自联接所以我把它留下了,但如果有必要可以加回来:

SELECT TOP 3
    a1.year,
    a1.quarter,
    a1.team,
    sum(a1.price) as Total

FROM
    tbl_sales a1

WHERE
     'some restrictions here'
     AND a1.quarter = 1 --(or however quarters are identified)
     AND a1.year = 2015 --(or however years are identified)

GROUP BY
    a1.year,
    a1.quarter,
    a1.team

ORDER BY 
    sum(a1.price) DESC

UNION ALL

SELECT TOP 3
    a2.year,
    a2.quarter,
    a2.team,
    sum(a2.price) as Total

FROM
    tbl_sales a2

WHERE
    'some restrictions here'
    AND a2.quarter = 2
    AND a2.year = 2015

GROUP BY
    a2.year,
    a2.quarter,
    a2.team

ORDER BY 
    sum(a2.price) DESC

UNION ALL

SELECT TOP 3
    a3.year,
    a3.quarter,
    a3.team,
    sum(a3.price) as Total

FROM
    tbl_sales a3

WHERE
    'some restrictions here'
    AND a3.quarter = 3
    AND a3.year = 2015

GROUP BY
    a3.year,
    a3.quarter,
    a3.team

ORDER BY 
    sum(a3.price) DESC

UNION ALL

SELECT TOP 3
    a1.year,
    a1.quarter,
    a1.team,
    sum(a1.price) as Total

FROM
    tbl_sales a4

WHERE
    'some restrictions here'
    AND a4.quarter = 4
    AND a4.year = 2015

GROUP BY
    a4.year,
    a4.quarter,
    a4.team

ORDER BY 
    sum(a4.price) DESC

正如你所看到的,除了where子句之外,表之间几乎没有区别,你不仅限于这4个表的联合,它只是一个例子,但请记住,如果你需要覆盖更多的季度你将需要添加更多要联合的表。 这可能变得非常笨拙,因为它要求您随着时间的推移不断向工会添加表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM