子查询组按月和年

时间:2016-06-21 21:11:54

标签: sql sql-server sql-server-2014

我有一个包含三列的表格:

id (nvarchar)
time (datetime)
description (nvarchar)

并想要计算以下数量:

SELECT 
(
(SELECT CAST(COUNT(DISTINCT id) as float)
FROM [table]
WHERE description = 'x'
) / 
(
(SELECT CAST(COUNT(DISTINCT id) as float)
FROM [table])
)
AS quotient

有没有办法计算每个月和每年的相同商数而不是整个表?我在最后尝试GROUP BY MONTH(time) + YEAR(time),但得到的错误是:

  

无法绑定多部分标识符。

1 个答案:

答案 0 :(得分:1)

试试这个:

SELECT YEAR(time), MONTH(time), 
       COUNT(DISTINCT CASE WHEN description = 'x' THEN id END)  /
       (COUNT(DISTINCT id) * 1.0) AS quotient
FROM [table]
GROUP BY YEAR(time), MONTH(time)