更新05/18/15
列上列有客户名称。如何在每个日期获得一个客户的百分比?例如
CustomerName Date
Sam 04/29/15
Joy 04/29/15
Tom 04/29/15
Sam 04/29/15
Oly 04/29/15
Joy 04/29/15
04/29/15
Sam 04/29/15
04/29/15
Sam 04/29/15
Oly 04/29/15
Sam 04/29/15
Oly 04/30/15
Joy 05/01/15
请注意,我的专栏有12条记录,其中2条是空白,但它们不会依赖于百分比,只有具有名称的记录。我想知道从总数中代表Sam的百分比(在这种情况下是10个记录,所以Sam%将是50)。
查询应返回
Date Percentage
04/29/15 50
04/30/15 0
05/01/15 0
更新
我并不关心其他客户,所以我们将它们视为一体。只需要知道总列表中Sam的百分比是多少。
任何帮助都将非常感激。谢谢
答案 0 :(得分:1)
您可以在子查询中计算每人+天的数字:
select Date
, CustomerName
, 100.0 * cnt / sum(cnt) over (partition by date)
from (
select Date
, CustomerName
, count(*) cnt
from table1
where CustomerName <> ''
group by
Date
, CustomerName
) t1
打印:
Date CustomerName
----------------------- ------------ ---------------------------------------
2015-04-29 00:00:00.000 Joy 20.000000000000
2015-04-29 00:00:00.000 Oly 20.000000000000
2015-04-29 00:00:00.000 Sam 50.000000000000
2015-04-29 00:00:00.000 Tom 10.000000000000
(4 row(s) affected)
答案 1 :(得分:0)
你会做这样的事情
SELECT (COUNT(*) * 100) / (SELECT COUNT(*) FROM Customer WHERE CustomerName <> '' AND Date = '04/29/15')
FROM Customer
WHERE CustomerName = 'Sam'
AND Date = '04/29/15'
如果您希望每个日期获得count
,则可以使用此
SELECT T.Date,((ISNULL(CustomerCount,0) * 100) / TotalCount)
FROM
(
SELECT COUNT(*) as TotalCount,Date
FROM Customer
WHERE CustomerName <> ''
GROUP BY Date
)T
LEFT JOIN
(
SELECT COUNT(*)
FROM Customer
WHERE CustomerName = 'Sam'
GROUP BY Date
)C
ON T.Date = C.Date
答案 2 :(得分:0)
你可以试试这个:
select name, date, (100.0 * count(*)) /
(select count(*) from table t2
where name is not null and name <> '' and t2.date = t1.date)
from table t1
where name is not null and name <> ''
group by name, date
答案 3 :(得分:0)
适用于所有用户
SELECT
(COUNT(*) * 100) / (SELECT COUNT(*) FROM Customer WHERE CustomerName <> '') as [percent],
CustomerName
FROM Customer group by CustomerName
用于特定用户
SELECT
(COUNT(*) * 100) / (SELECT COUNT(*) FROM Customer WHERE CustomerName <> '') as [percent],
CustomerName
FROM Customer where CustomerName ='Sam'