Count(*)乘以PL SQL开发人员中的一些值

时间:2013-10-08 16:45:11

标签: sql database oracle

当我使用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

我收到这些值 -

enter image description here

但是,这是错误的,因为当我使用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

我收到这些值 -

enter image description here

如何更正fisrt select语句中的计数,以便我可以收到正确的值?

3 个答案:

答案 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