SQL-计算按月分组的百分比列

时间:2018-08-24 13:09:02

标签: sql-server tsql grouping

我有一个表,其中有一个用于时间戳的日期时间列和一个用于通过/失败的比特列,例如

Timestamp                     Pass
2018-01-19 07:01:42.000         1
2018-01-19 07:05:42.000         0

我可以按年/月分组以显示每月的总通行证:

SELECT  DATEPART(YEAR,Timestamp) AS Year,
        DATEPART(MONTH,Timestamp) AS Month,
        COUNT(Timestamp) as Total
    FROM table
    WHERE Pass  = 1
GROUP BY DATEPART(YEAR,Timestamp), DATEPART(MONTH,Timestamp)
ORDER BY DATEPART(YEAR,Timestamp), DATEPART(MONTH,Timestamp)

我还需要显示每月的总结果(通过和失败),并尽可能显示通过的百分比,例如。

Year    Month    Passes   Total   Percentage Pass
2018      1       2729     3275       83.32

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

SELECT  DATEPART(YEAR,Timestamp) AS Year,
        DATEPART(MONTH,Timestamp) AS Month,
        SUM(CAST(Pass AS INT)) AS Passes,
        COUNT(*) as Total,
        CAST(1.00*SUM(CAST(Pass AS INT)) / COUNT(*) AS DECIMAL(5,2) AS PercentagePass -- 1.00 is used to avoid integer maths
FROM table
GROUP BY DATEPART(YEAR,Timestamp), DATEPART(MONTH,Timestamp)
ORDER BY DATEPART(YEAR,Timestamp), DATEPART(MONTH,Timestamp)

答案 1 :(得分:2)

.parent{
    opacity: 0.3;
}

.child{
    background-color:rgba(0,0,0,1);
}