祝贺所有人。我有一个SQL 2008 express数据库,让name为tbl_Merchant,类似如下:
Merchant | Sales | Month
Comp.1 100 1
Comp.2 230 1
Comp.3 120 1
Comp.1 200 2
Comp.2 130 2
Comp.3 240 2
Comp.1 250 3
. . .
. . .
. . .
我需要在12个月内找到每月销售额排名前10位的商家。
如果仅仅一个月就很容易。
SELECT TOP 10
Merchant,
Sales,
Month
FROM tbl_Merchant
WHERE Month = 1
ORDER BY Sales DESC
但如果我想在12个月内找到它们,我就会陷入困境。我需要展示120个商家,这是每个月的前十大销售商。目前我的解决方案是将第1个月到第12个月的12个表合并在一起,但我不认为这是一个好方法。
任何人都可以给我任何建议吗?
非常感谢。
答案 0 :(得分:4)
适用于Sql Server 2005 +
整体尝试:
SELECT TOP 10
Merchant,
SUM(Sales) Sales
FROM tbl_Merchant
WHERE Month BETWEEN 1 and 12
GROUP BY Merchant
ORDER BY 2 DESC
或
如果您每月需要详细信息,前10名每月
;WITH MonthsCTE(m) as
(
SELECT 1 m
UNION ALL
SELECT m+1
FROM MonthsCTE
WHERE m < 12
)
SELECT m [Month], t.*
FROM MonthsCTE
CROSS APPLY
(
SELECT TOP 10
Merchant,
SUM(Sales) Sales
FROM tbl_Merchant
WHERE Month = MonthsCTE.m
GROUP BY Merchant
ORDER BY 2 DESC
) t
答案 1 :(得分:2)
尝试:
select * from
(SELECT Merchant,
Sales,
Month,
row_number () over (partition by Month order by Sales desc) rn
FROM tbl_Merchant
WHERE Month between 1 and 12) v
where rn <= 10
order by Month, Sales desc
(应该在SQLServer中工作;不确定Sybase。)
答案 2 :(得分:0)
select Top 10
SaleID,
sum(Salelines) As LINESUM
Into #TOP10sales
from salestable
group by SaleID
order by sum(Salelines) asc;
Then confirm the sales are top 10
select *
from #TOP10sales;
Then.
Select field..
field..
field..
from #TOP10sales
Inner Join salestable on #TOP10sales.ID = salestable.ID;
答案 3 :(得分:-1)
可以尝试以下方法:
SELECT top 10 Merchant,
isnull(SUM(CASE WHEN Month(ta.dt) = '01' THEN Sales END),0) AS "Jan Sales",
isnull(SUM(CASE WHEN Month(ta.dt) = '02' THEN Sales END),0) AS "Feb Sales",
isnull(SUM(CASE WHEN Month(ta.dt) = '03' THEN Sales END),0) AS "Mar Sales",
isnull(SUM(CASE WHEN Month(ta.dt) = '04' THEN Sales END),0) AS "Apr Sales",
isnull(SUM(CASE WHEN Month(ta.dt) = '05' THEN Sales END),0) AS "May Sales",
isnull(SUM(CASE WHEN Month(ta.dt) = '06' THEN Sales END),0) AS "Jun Sales",
isnull(SUM(CASE WHEN Month(ta.dt) = '07' THEN Sales END),0) AS "Jul Sales",
isnull(SUM(CASE WHEN Month(ta.dt) = '08' THEN Sales END),0) AS "Aug Sales",
isnull(SUM(CASE WHEN Month(ta.dt) = '09' THEN Sales END),0) AS "Sep Sales",
isnull(SUM(CASE WHEN Month(ta.dt) = '10' THEN Sales END),0) AS "Oct Sales",
isnull(SUM(CASE WHEN Month(ta.dt) = '11' THEN Sales END),0) AS "Nov Sales",
isnull(SUM(CASE WHEN Month(ta.dt) = '12' THEN Sales END),0) AS "Dec Sales"
FROM tbl_Merchant ORDER BY Sales DESC
每个月的十大销售额将按月显示为不同的列。
希望它有所帮助。
答案 4 :(得分:-1)
每月前10名的详细信息也可以使用此查询得出
选择商家,SUM(销售)Total_sales,月份为Monthofyear
来自tbl_Merchant
按月分组,商家,销售
按月销售,销售额说明
答案 5 :(得分:-2)
select top 10 Merchant, sum(Sales) from tbl_Merchant group by Merchant order by sum(Sales) desc
我更喜欢postgresql,但我认为它可以在没有(或很少)修改mssql的情况下工作