我有一张桌子,每位销售人员每天销售1条记录
NAME DATE
joe 1-1-13
joe 1-1-13
joe 1-1-13
dave 1-1-13
joe 1-2-13
我用它来创造&填充表格
create table #sales (name varchar(10), salesdate date )
insert into #sales (name, salesdate)
values ('joe', '01-01-2013'), ('joe','01-01-2013'),
('joe', '01-01-2013'), ('dave','01-01-2013'),
('joe','01-02-2013')
我想要一个查询来提高每个销售人员的销售额百分比
(例如,在1-1-13乔当天共有4个单位出售3个单位(75%) 但我不知道SQL如何能够提高当天所有销售额的总和,无论销售人员如何
这和我一样接近。
select name, salesdate, count(*) as "dailyTotal"
from #sales
group by name, salesdate
如何包含每日总数,以便它可用于计算当天的总百分比?
答案 0 :(得分:10)
不是最优雅的方式,但你可以试试这个 -
select [name],[salesdate], COUNT(*) as dayTotal,
SUM(COUNT(*)) over() as AllSales,
(COUNT(*) * 1.0) / SUM(COUNT(*)) over() as dayPercent
FROM [dbo].[sales]
group by [name], [salesdate]
我删除了表名中的#。顺便说一下,这段代码依赖于OVER()子句。您可以了解如何自己截断多余的零。
name salesdate dayTotal AllSales dayPercent
dave 2013-01-01 1 5 0.200000000000
joe 2013-01-01 3 5 0.600000000000
joe 2013-01-02 1 5 0.200000000000
HTH。
如果该查询看起来过于复杂,请先查看此问题。它会让你知道我想要做什么。
select [name],[salesdate], COUNT(*) as dayTotal,
SUM(COUNT(*)) over() as AllSales
FROM [dbo].[sales]
group by [name], [salesdate]
答案 1 :(得分:4)
最受欢迎的答案似乎不正确。
OP有预期答案
例如1-1-13岁的乔当天共有4个单位(75%)出售了3个单位
然而得到的回答显示为60%。
不是对所有数据进行求和,而是应该按天划分,这是一个更好的例子:
select [name],[salesdate], COUNT(*) as dayTotal,
SUM(COUNT(*)) over(PARTITION BY salesdate) as AllDaySales,
(COUNT(*) * 1.0) / SUM(COUNT(*)) over(PARTITION BY salesdate) as dayPercent
FROM [dbo].[sales]
group by [name], [salesdate]
答案 2 :(得分:2)
使用嵌套查询获取每日总数:
BEGIN
create table #sales (name varchar(10), salesdate date )
insert into #sales (name, salesdate) values
('joe', '01-01-2013'),
('joe', '01-01-2013'),
('joe', '01-01-2013'),
('dave', '01-01-2013'),
('joe', '01-02-2013'),
('dave', '01-02-2013')
SELECT name, salesdate, COUNT(*) AS personDailyTotal, MAX(dailyTotal) AS dailyTotal,
(COUNT(*) * 100.0) / MAX(dailyTotal) AS [Percent]
FROM #sales
INNER JOIN (
SELECT salesdate as [day], COUNT(*) as dailyTotal
FROM #sales
GROUP BY salesdate
) AS [Total] ON salesdate = [day]
GROUP BY name, salesdate
END
答案 3 :(得分:0)
- 使用以下查询
select T1.salesdate, name ,convert(numeric(18,2),convert(decimal,count(*)) * 100 / T2.total) as percentage from #sales T1
inner join (
select salesdate,count(*) as total from #sales group by salesdate
) as T2
on T1.salesdate = T2.salesdate
group by name,T1.salesdate,T2.total