SQL除以id并按组分组

时间:2012-09-13 17:14:05

标签: sql sql-server database sql-server-2008

我在下面有以下查询。我正在尝试使用特定条件提取记录数,然后除以按cstmr_id分组的记录总数。但是我收到了一个错误。任何帮助,将不胜感激。此外,此语句是子查询,是更大的选择查询的一部分。我正在使用SQL Server 2005

在'/'附近获取“语法不正确”错误

说明:

((SELECT count(*) FROM cstmr WHERE active=1 AND cstmr_type LIKE '%dtr%' 
GROUP BY cstmr_id) 
/  --division sign here. dividing top query by bottom
(SELECT count(*) FROM cstmr WHERE cstmr_type LIKE '%dtr%'
GROUP BY cstmr_id) ) As cstmr_rate

cstmr表中的示例数据:

cstmr_id    cstmr_type    active
3423        dtr           1
1236        dtr           1
1842        dtr           1
8273        sys           2
9384        aod           1
3847        sys           2

预期结果样本:

cstmr_id    cstmr_rate
3423        88.98
1236        25.21
1842        58.01

基本伪代码

仅选择“dtr”类型的活跃客户,然后除以客户总数。然后为每个客户显示此衍生比率。这是一个非常基本的等式,使用相同的表“cstr”

4 个答案:

答案 0 :(得分:3)

;WITH x AS 
(
  SELECT cstmr_id, active, c = COUNT(*) 
   FROM dbo.cstmr WHERE cstmr_type LIKE '%dtr%'
   GROUP BY cstmr_id, active
), 
cr(cstmr_id, cstmr_rate) AS
(
  SELECT cstmr_id, 
   SUM(CASE active WHEN 1 THEN c ELSE 0 END)*1.0 / SUM(c) 
  FROM x GROUP BY cstmr_id
)
SELECT cr.cstmr_id, cr.cstmr_rate --, other columns
FROM cr
--INNER JOIN -- other tables from your larger query

答案 1 :(得分:2)

您似乎缺少外部SELECT

select -- You are missing this
(
    (SELECT cast(count(*) as decimal(10,2))
    FROM cstmr 
    WHERE active=1 AND cstmr_type LIKE '%dtr%' 
    GROUP BY cstmr_id) 
/  --division sign here. dividing top query by bottom
    (SELECT cast(count(*) as decimal(10,2))
    FROM cstmr 
    WHERE cstmr_type LIKE '%dtr%'
    GROUP BY cstmr_id) 
) As cstmr_rate

答案 2 :(得分:1)

除了语法问题之外,还有更简单的方法来表达您想要的内容:

select count(distinct case when active = 1 then cstmr_id end)*1.0 / count(distinct cstmr_id)
from cstmr
where cstmr_type like '%dtr%'

如果cstmr表中没有重复cstmr_id,您可以进一步简化为:

select sum(case when active = 1 then 1.0 else 0.0 end) / count(*)
from cstmr
where cstmr_type like '%dtr%'

甚至:

select avg(active*1.0)
from cstmr
where cstmr_type like '%dtr%'

请注意,我还将整数转换为浮点数。正如你所写的那样,它产生的值是0或1,因为SQL Server对整数进行整数运算。

答案 3 :(得分:1)

它可能无法正常工作,因为这两个查询返回的是多条记录。 SQL Server无法按结果集划分结果集。

尝试使用连接来取代这些计数。

修改

这样的事情:

SELECT 
    c.cstmr_id,
    c1/c2 AS 'cstmr_rate'
FROM cstmr as c
JOIN (
    SELECT cstmr_id, count(*) AS 'c1'
    FROM cstmr 
    WHERE active=1 
    AND cstmr_type LIKE '%dtr%' 
    GROUP BY cstmr_id
    ) AS sub1 ON c.cstmr_id = sub1.cstmr_id
JOIN (
    SELECT cstmr_id, count(*) AS 'c2'
    FROM cstmr 
    WHERE cstmr_type LIKE '%dtr%'
    GROUP BY cstmr_id
    ) AS sub2 ON c.cstmr_id = sub2.cstmr_id

EDIT2

假设active为1或0:

,这也可能有效
SELECT
    cstmr_id,
    SUM(Active)/COUNT(*)  AS 'cstmr_rate'
FROM cstmr
GROUP BY cstmr_id