我在表格中有2个列... 这是:
HCode No_of contacts
AA1 78
AA2 10
AA3 09
AA4 14
AA5 10
AA1 21
我写了以下代码:
select HCode, Sum(No_of contacts) as NoOFContacts
from #T
Group by HCode
order by HCode
使用上面的代码,如何根据max([No_of contacts])填充Percentage列?
答案 0 :(得分:1)
也许这就是你想要的?
select
HCode,
Sum([No_of contacts]) as NoOFContacts,
Sum([No_of contacts])*100/(select Sum([No_of contacts]) from #t) as Percentage
from #t
Group by HCode
order by HCode
这会产生以下结果:
HCode NoOFContacts Percentage
---------- ------------ -----------
AA1 99 69
AA2 10 7
AA3 9 6
AA4 14 9
AA5 10 7
(5 row(s) affected)
答案 1 :(得分:0)
您可以使用嵌套的sql语句
来实现select Hcode, (NumberAcc/SumAcc)*100 as Percentage, Sumacc
from
(select Hcode, Sum(no_Of contacts) as SumAcc, no_OfContacts as NumberAcc
from #t
group by HCode, no_OfContacts) as T
答案 2 :(得分:0)
您可以尝试使用以下查询:
select HCode,Sum(No_of contacts ) as NoOFContacts,(Sum(No_of contacts)*100/(Select Count(*) from #T)) as Percentage
from #T
group by HCode
order by HCode
答案 3 :(得分:0)
您可以使用Analytical functions获取最大合同数量,而无需单独使用子句来获取此合同:
CREATE TABLE #T (HCode VARCHAR(3), No_of_contacts INT);
INSERT #T (HCode, No_of_contacts)
VALUES ('AA1', 78), ('AA2', 10), ('AA3', 09),
('AA4', 14), ('AA5', 10), ('AA1', 21);
SELECT HCode,
No_of_contacts,
PercentOfContracts = 100.0 * No_of_contacts / MAX(No_of_contacts) OVER()
FROM ( SELECT HCode,
No_of_contacts = SUM(No_of_contacts)
FROM #T
GROUP BY Hcode
) AS t;