Pl sql ...查找出现次数

时间:2011-04-18 08:16:34

标签: plsql oracle9i

假设我有一个日期

的第2条记录

table1有2组记录

key1 startdate1  startdate2 startdate3
100  2349         2456       2345
100  3456         3878       2872

日期是二进制格式。我需要获得日期更改的计数,这意味着在一个特定日期之后日期更改的次数 即,假设在2011年4月14日之后,日期发生变化的次数(针对特定key_1的这两个记录)

澄清

假设我有三条记录:

+------+-------------+-------------+-------------+
| key1 | start_date1 | start_date2 | start_date3 |
+------+-------------+-------------+-------------+
| 701  | 08-SEP-2009 | 08-DEC-2009 | 08-jan-2010 |
| 701  | 08-JUN-2013 | 08-SEP-2013 | 08-DEC-2013 |
| 701  | 08-MAR-2017 | 08-MAR-2018 | 31-DEC-1899 |
+------+-------------+-------------+-------------+

我需要计算大于14-apr-2011的更改日期。例如,对于密钥701,有大约5个更改日期大于2011年4月14日。我需要获得一个包含两个字段的表输出:

+------+---------------+
| Key1 | changedcount  |
+------+---------------+
| 701  | 5             |
+------+---------------+

3 个答案:

答案 0 :(得分:1)

尝试规范化你的表格:

WITH
  normalized_data AS
  (
    SELECT key1, start_date1 AS start_date FROM MYTABLE
  UNION ALL
    SELECT key1, start_date2 AS start_date FROM MYTABLE
  UNION ALL
    SELECT key1, start_date3 AS start_date FROM MYTABLE
  )

SELECT
  key1,
  COUNT(DISTINCT start_date) AS changedcount
FROM
  normalized_data
WHERE
  start_date > your_start_date_here
GROUP BY
  key1

答案 1 :(得分:0)

现在您提出了更明确的问题:

select key1, count(distinct start_date)
from (
    select key1, start_date1 as start_date from myTable
    UNION ALL
    select key1, start_date2 as start_date from myTable
    UNION ALL
    select key1, start_date3 as start_date from myTable
) normalFormTable N
where start_date > myGivenDate
group by key

答案 2 :(得分:0)

你可以试试这个:

select sum(d1)+sum(d2)+sum(d3) , key
 from
(
select
  t.key,
  (select count(*) from test t1 where t1.key = t.key and start_date1>to_date('14-Apr-2011','DD-mon-yyyy')) d1,
  (select count(*) from test t2 where t2.key = t.key  and start_date2>to_date('14-Apr-2011','DD-mon-yyyy')) d2,
  (select count(*) from test t3 where t3.key = t.key  and start_date3>to_date('14-Apr-2011','DD-mon-yyyy')) d3
from  test t
group by key
)
group by key

如果您使用的是11g或以上,您也可以尝试ORACLE PIVOT()功能。我目前没有安装11g,但如果你需要一个例子,我可以给你一个这个功能。

此致 亚历

相关问题