尝试将两列分开以获取百分比,但给我0

时间:2019-02-08 16:01:08

标签: sql sql-server format

目标:我试图获取两列之间的百分比差异,但我认为问题出在该列的类型中。

情况:我有两列我必须计算NON NULL次发生,以查明每个月发生某事的次数。我想得到这两列之间的百分比差异。

查询:

SELECT *
    ,subquery3.[Email Logins Week2]/subquery3.[Email Logins Week1]
FROM    (
        SELECT  
             FORMAT(tbl3.Creation_Date, 'yyyyMM')       AS [Date Subscribed]
            ,CAST(COUNT(CASE WHEN t1.Emails IS NOT NULL THEN 1 ELSE NULL END) AS int)   AS [Email Logins Week1]
            ,CAST(COUNT(CASE WHEN t2.Emails IS NOT NULL THEN 1 ELSE NULL END) AS int)   AS [Email Logins Week2]
        FROM #tbl1 t1
        LEFT JOIN #tbl2 t2
            ON t1.Emails=t2.Emails
        INNER JOIN #tbl3 t3
            ON t1.Emails=t3.email
        GROUP BY FORMAT(t3.Creation_Date, 'yyyyMM')
        ) subquery3

这给了我类似的东西:

+-----------------+--------------------+--------------------+------------------+
| Date Subscribed | Email Logins Week1 | Email Logins Week2 | (No column name) |
+-----------------+--------------------+--------------------+------------------+
|          201801 |               6800 |               2000 |                0 |
|          201802 |               9000 |               3000 |                0 |
|          201803 |               7000 |               2500 |                0 |
|          201804 |               7200 |               2400 |                0 |
+-----------------+--------------------+--------------------+------------------+

代替:

+-----------------+--------------------+--------------------+------------------+
| Date Subscribed | Email Logins Week1 | Email Logins Week2 | (No column name) |
+-----------------+--------------------+--------------------+------------------+
|          201801 |               6800 |               2000 |      0.294117647 |
|          201802 |               9000 |               3000 |      0.333333333 |
|          201803 |               7000 |               2500 |      0.357142857 |
|          201804 |               7200 |               2400 |      0.333333333 |
+-----------------+--------------------+--------------------+------------------+

奖励:是否可以在子查询中获得差值%,以便不创建子查询????

1 个答案:

答案 0 :(得分:2)

这应该为您提供“奖金”的答案。还要在下面注意我的其他评论:

SELECT LEFT(CONVERT(varchar(8),t3.Creation_Date,112),6) AS [Date Subscribed], --FORMAT performs poorly, this'll be faster
       COUNT(CASE WHEN t1.Emails IS NOT NULL THEN 1 END) AS [Email Logins Week1], --COUNT already returns an int
       COUNT(CASE WHEN t2.Emails IS NOT NULL THEN 1 END) AS [Email Logins Week2], --I've also removed the ELSE NULL as a CASE expression that doesn't resolve returns NULL
       COUNT(CASE WHEN t1.Emails IS NOT NULL THEN 1 END) / (COUNT(CASE WHEN t2.Emails IS NOT NULL THEN 1 END) * 1.0) AS OtherColumn
FROM #tbl1 t1
     LEFT JOIN #tbl2 t2 ON t1.Emails = t2.Emails
     INNER JOIN #tbl3 t3 ON t1.Emails = t3.email
GROUP BY LEFT(CONVERT(varchar(8),t3.Creation_Date,112),6);