0

当我在 case 语句中使用 count (*) 乘以某个值时出现问题。

这是我的代码 -

  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

我收到了这些价值观——

在此处输入图像描述

如何更正第一个 select 语句中的计数,以便接收正确的值?

4

3 回答 3

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
于 2013-10-08T16:48:49.483 回答
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
于 2013-10-08T16:54:49.843 回答
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    
于 2013-10-08T18:07:42.663 回答