0

我在下面有以下查询。我正在尝试提取具有特定条件的记录数,然后除以按 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

4 回答 4

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
于 2012-09-13T18:16:16.167 回答
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
于 2012-09-13T17:21:14.833 回答
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

编辑2

假设 active 为 1 或 0,这也可能有效:

SELECT
    cstmr_id,
    SUM(Active)/COUNT(*)  AS 'cstmr_rate'
FROM cstmr
GROUP BY cstmr_id
于 2012-09-13T17:50:32.673 回答
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_id 在 cstmr 表中没有重复,您可以进一步简化为:

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 对整数进行整数运算。

于 2012-09-13T17:28:24.120 回答