[英]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中,您可以使用IN
和TOP
執行此操作:
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.