SQL Server十进制除法返回1.000

时间:2019-04-18 15:01:42

标签: sql sql-server

我正在尝试根据电子邮件发送的总价值来计算一些百分比。我一直在努力找出为什么我的除法计算未返回预期结果的原因。

我正在尝试返回与总发送量有关的每个项目的百分比值。例如。退订/发送总数= 0.1%|

我整天都在注视着这件事,似乎无法超越这一点,所以我真的认为我错过了那么小而愚蠢的事情。

这是显示问题的查询/结果的图片:

enter image description here

在FROM之前,我评论了我为解决该问题而写的几行,请不要嘲笑我! :P

SELECT
    'Unsubscribes' AS 'Type',
    COUNT(e.eventid) AS 'Total',
    -- e2.all_values AS 'Total',
    -- ISNULL(NULLIF(COUNT(CAST(e.eventid AS DECIMAL(15,2))), 0) / 
    COUNT(CAST(e2.all_values as decimal(15,2))),0) AS '%',
    -- CAST(COUNT(e.EventID) as decimal(15,2)) / CAST(COUNT(e2.all_values) AS DECIMAL(15,2)) AS '%'
    CONVERT(DECIMAL(15,2), COUNT(e.EventID)) /  CONVERT(DECIMAL(15,2), 
    COUNT(e2.all_values)) AS '%'
    COUNT(e2.all_values))
FROM 
    XMPDBTRACKING.XMPieTracking.Event e
LEFT JOIN 
    (SELECT
         COUNT(e2.eventid) AS 'all_values',
         MarketingCampaignID
     FROM 
         xmpdbtracking.xmpietracking.event e2
     WHERE 
         e2.marketingcampaignid = 16704
         AND e2.eventtypeid IN (20)
     GROUP BY 
         MarketingCampaignID) e2 ON e2.MarketingCampaignID = e.MarketingCampaignID
 WHERE 
     e.MarketingCampaignID = 16704
     AND e.EventTypeID IN (24)

我正在尝试将退订/总发送的值作为%值返回

Total Send  4366    100.000000000000000000
Unsubscribes    65  1.000000000000000000

2 个答案:

答案 0 :(得分:0)

尝试更改此行:

CONVERT(DECIMAL(15,2), COUNT(e.EventID)) / CONVERT(DECIMAL(15,2), COUNT(e2.all_values)) AS '%'

至:

CONVERT(DECIMAL(15,2), CONVERT(DECIMAL(15,2), COUNT(e.EventID)) / CONVERT(DECIMAL(15,2), COUNT(e2.all_values)) AS '%

也许是因为计数结果是整数而不是十进制。

答案 1 :(得分:0)

您的主要查询中包括了未订阅的内容,对不对? LEFT外部联接意味着它将仅匹配主查询中存在的行。因此,您只查询“退订”。

如何(未试用)

;WITH sums AS
(
  SELECT MarketingCampaignID
  ,      SUM(CASE EventTypeID WHEN 20 THEN 1 ELSE 0 END) AS Event20
  ,      SUM(CASE EventTypeID WHEN 24 THEN 1 ELSE 0 END) AS Event24
  GROUP BY MarketingCampaignID
)
SELECT MarketingCampaignID
,      CAST(Event24 as decimal(15,2)) / CAST(Event20 AS decimal(15,2))
FROM sums