[英]SQL divide and group by id
我在下面有以下查詢。 我試圖提取具有特定條件的記錄數,然后除以cstmr_id分組的記錄總數。 但是我遇到一個錯誤。 任何幫助,將不勝感激。 另外,該語句是子查詢,是較大的select查詢的一部分。 我正在使用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”
;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
看來您缺少外部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
除了語法問題之外,還有其他更簡單的方法來表達您想要的內容:
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對整數進行整數運算。
這可能不起作用,因為這兩個查詢返回的記錄多於一條。 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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.