当我使用count(*)乘以case语句中的某个值时,我遇到了问题。
这是我的代码 -
SELECT DISTINCT
plmn,
CASE
WHEN timestamp < '20130300' THEN (COUNT (*) * 0.02)
ELSE (COUNT (*) * 0.03)
END
AS total
FROM tap_out
WHERE teleservicecode = '22' AND calltype = 'MOC'
-- AND timestamp LIKE '201303%'
GROUP BY plmn, timestamp
我收到这些值 -
但是,这是错误的,因为当我使用count(*)乘以某个值而不是在case语句中我收到其他值。这是代码 -
SELECT DISTINCT
plmn, count (*) * 0.02 AS total
FROM tap_out
WHERE teleservicecode = '22'
AND calltype = 'MOC'
-- AND timestamp LIKE '201303%'
GROUP BY plmn
我收到这些值 -
如何更正fisrt select语句中的计数,以便我可以收到正确的值?
答案 0 :(得分:4)
与案件无关。在第二个查询中,您不按时间戳分组,因此您很可能拥有更高的计数和更少的总记录。第一个查询将返回更多,更多的记录,但您使用distinct
过滤所有记录。
试试这个:
SELECT
plmn,
COUNT(*) * Multiplyer AS total
FROM
(SELECT
plmn,
CASE WHEN timestamp < '20130300' THEN
0.02
ELSE
0.03
END AS Multiplyer
FROM
tap_out
WHERE
teleservicecode = '22' AND calltype = 'MOC')
GROUP BY
plmn,
Multiplyer
答案 1 :(得分:1)
尝试写下这样的查询:
-- then I sum the value for plmn
SELECT plmn,
sum(val) total
FROM (
-- first I calculate the value for each plmn/timestamp couple
SELECT plmn,
CASE
WHEN timestamp < '20130300' THEN (COUNT (*) * 0.02)
ELSE (COUNT (*) * 0.03)
END
AS val
FROM tap_out
WHERE teleservicecode = '22' AND calltype = 'MOC'
-- AND timestamp LIKE '201303%'
GROUP BY plmn, timestamp
)
GROUP BY plmn
答案 2 :(得分:1)
这是你需要的吗?
SELECT plmn,
Sum(CASE
WHEN timestamp < '20130300'
THEN 0.02
ELSE 0.03
END)
AS total
FROM tap_out
WHERE teleservicecode = '22' AND
calltype = 'MOC'
GROUP BY plmn