如何使用SQL获取计数和百分比?

时间:2015-01-06 06:08:54

标签: sql sql-server

下面给出的是数据库表(TableA)。

SlNo  TeamName  WorkInfo 
----  -------   -------  
1     Team1        0    
2     Team1        0    
3     Team1        1     
4     Team2        1    
5     Team2        1 
6     Team2        1      
7     Team3        0      
8     Team3        1      

我有两个文本框用于选择开始和结束日期。我想在那些日期之间显示细节。

鉴于以下查询,我们会根据开始日期和结束日期提供详细信息和计数。

SELECT TeamName,Count(DISTINCT CASE WHEN WorkInfo = 1 THEN SlNo end) AS Count1 , 
       Count(DISTINCT CASE WHEN WorkInfo = 0 THEN SlNo end) AS Count0 FROM tableA 
WHERE (SubmitDate BETWEEN @start AND @end) GROUP BY TeamName

以上查询显示如下所示的输出:

TeamName   Count1   Count0
--------   -----    ------
Team1        1        2
Team2        3        0
Team3        1        1

我想根据greatest countCount1中的Count0显示百分比。帮我修改上面的解决方案。 The expecting output sample is given below:

这里Count1 3是greates值。基于此我必须找到Count1值的百分比。在Count0 2中是最大的值。基于此我必须找到Count0值的百分比。

TeamName   Count1   Count0  Percentage1  Percentage0
--------   -----    ------  -----------  -----------
Team1        1        2        33.33%         100%
Team2        3        0        100%           0%
Team3        1        1        33.33%         50%  

帮我找到合适的解决方案。谢谢。

3 个答案:

答案 0 :(得分:0)

要在SQL中显示百分比,我们希望利用我们用于排名/运行总计加子查询的想法。与我们在SQL子查询部分中看到的不同,这里我们要将子查询用作SELECT的一部分。让我们用一个例子来说明。假设我们有下表,

Name    Sales
John    10
Jennifer    15
Stella  20
Sophia  40
Greg    50
Jeff    20

我们会打字,

SELECT a1.Name, a1.Sales, a1.Sales/(SELECT SUM(Sales) FROM Total_Sales) Pct_To_Total 
FROM Total_Sales a1, Total_Sales a2 
WHERE a1.Sales <= a2.sales or (a1.Sales=a2.Sales and a1.Name = a2.Name) 
GROUP BY a1.Name, a1.Sales 
ORDER BY a1.Sales DESC, a1.Name DESC;

结果:

Name    Sales   Pct_To_Total
Greg    50  0.3226
Sophia  40  0.2581
Stella  20  0.1290
Jeff    20  0.1290
Jennifer    15  0.0968
John    10  0.0645

子查询SELECT SUM(Sales) FROM Total_Sales计算总和。然后我们可以用这个总和来划分各个值,以获得每行的总百分比。

参考是here

答案 1 :(得分:0)

这是你要问的还是我完全错了?

exec ('SELECT TeamName,Count(DISTINCT CASE WHEN WorkInfo = 1 THEN SlNo end) AS Count1 , Count(DISTINCT CASE WHEN WorkInfo = 0 THEN SlNo end) AS Count0, ((Count(DISTINCT CASE WHEN WorkInfo = 1 THEN SlNo end)/'+ @totaldays + ')*100) as Percentage1, ((Count(DISTINCT CASE WHEN WorkInfo = 0 THEN SlNo end)/' + @totaldays + ')*100) as Percentage0 FROM tableA WHERE (SubmitDate BETWEEN ' + @start ' + AND ' + @end + ') GROUP BY TeamName')

答案 2 :(得分:0)

如果百分比基于开始日期和结束日期的不同日期,而不是数据本身

SELECT 
  TeamName,
  Count(DISTINCT CASE WHEN WorkInfo = 1 THEN SlNo end) AS Count1, 
  Count(DISTINCT CASE WHEN WorkInfo = 0 THEN SlNo end) AS Count0,
  Count(DISTINCT CASE WHEN WorkInfo = 1 THEN SlNo end) * 100.0 / (DATEDIFF(Day, @start, @end) + 1) AS Percentage1,
  Count(DISTINCT CASE WHEN WorkInfo = 0 THEN SlNo end) * 100.0 / (DATEDIFF(Day, @start, @end) + 1) AS Percentage0
FROM 
  tableA 
WHERE 
  (SubmitDate BETWEEN @start AND @end) 
GROUP BY 
  TeamName