获得数字的百分比

时间:2017-09-19 11:37:24

标签: sql-server

我认为这是一个时髦的舍入问题,但我不知道内部sql是如何工作的。所以也许有人可以提供帮助。

   SELECT COUNT(Id) TotalReferrals,
   SUM(CASE WHEN NHSCommunicationNeed1_Id IS NOT NULL THEN 1 ELSE 0 END) NHSCommNeed1Total, 
   SUM(CASE WHEN NHSCommunicationNeed2_Id IS NOT NULL THEN 1 ELSE 0 END) NHSCommNeed2Total,
   SUM(CASE WHEN NHSCommunicationNeed3_Id IS NOT NULL THEN 1 ELSE 0 END) 
   NHSCommNeed3Total
   INTO #Totals
   FROM DDS.Referrals

给我以下结果集

TotalReferrals  NHSCommNeed1Total   NHSCommNeed2Total   NHSCommNeed3Total
1008            1008                508                 508

然后当我这样做时

SELECT 
   SUM((NHSCommNeed1Total / TotalReferrals) * 100) NHSCommNeed1Percent, 
   SUM((NHSCommNeed2Total / TotalReferrals) * 100) NHSCommNeed2Percent,
   SUM((NHSCommNeed3Total / TotalReferrals) * 100) NHSCommNeed3Percent
FROM #Totals

我明白了吗?

NHSCommNeed1Percent NHSCommNeed2Percent NHSCommNeed3Percent
100                 0                   0

有人可以解释发生了什么以及如何解决它

2 个答案:

答案 0 :(得分:2)

NHSCommNeed1Total / (TotalReferrals的结果计算为整数,因此最终为0.要强制将其设为十进制或双精度,只需将其与1.0相乘:

SELECT 
   SUM((NHSCommNeed1Total / (TotalReferrals * 1.0)) * 100) NHSCommNeed1Percent, 
   SUM((NHSCommNeed2Total / (TotalReferrals * 1.0)) * 100) NHSCommNeed2Percent,
   SUM((NHSCommNeed3Total / (TotalReferrals * 1.0)) * 100) AS NHSCommNeed3Percent
FROM #Totals

是的,不需要两个陈述,您可以使用INSERT INTO SELECT

WITH CTE
AS
(
    SELECT COUNT(Id) TotalReferrals,
       SUM(CASE WHEN NHSCommunicationNeed1_Id IS NOT NULL THEN 1.0 ELSE 0 END) NHSCommNeed1Total, 
       SUM(CASE WHEN NHSCommunicationNeed2_Id IS NOT NULL THEN 1.0 ELSE 0 END) NHSCommNeed2Total,
       SUM(CASE WHEN NHSCommunicationNeed3_Id IS NOT NULL THEN 1.0 ELSE 0 END) 
       NHSCommNeed3Total
       FROM DDS.Referrals
)
INSERT INTO SomeOtherTable(NHSCommNeed1Total,NHSCommNeed2Total ,NHSCommNeed3Total)
SELECT
  SUM((NHSCommNeed1Total / (TotalReferrals * 1.0)) * 100) AS NHSCommNeed1Percent, 
  SUM((NHSCommNeed2Total / (TotalReferrals * 1.0)) * 100) NHSCommNeed2Percent,
  SUM((NHSCommNeed3Total / (TotalReferrals * 1.0)) * 100) AS NHSCommNeed3Percent
FROM CTE;

答案 1 :(得分:0)

如果你想要一个一体化的陈述,这应该有效

SELECT 
SUM(CASE WHEN NHSCommunicationNeed1_Id IS NOT NULL THEN 1.0 ELSE 0.0 END) / COUNT(Id)  as NHSCommNeed1Percent, 
SUM(CASE WHEN NHSCommunicationNeed2_Id IS NOT NULL THEN 1.0 ELSE 0.0 END) / COUNT(Id)  as NHSCommNeed2Percent,
SUM(CASE WHEN NHSCommunicationNeed3_Id IS NOT NULL THEN 1.0 ELSE 0.0 END) / COUNT(Id)  as NHSCommNeed3Percent
FROM DDS.Referrals