SQL - 从TableA中选择,然后从TableA中选择Count

时间:2018-01-02 19:02:15

标签: sql oracle select count

我有TableA。它有一个按日期列出的ID数据。

ID可以有多条记录。

ID STARTDATE
-- ------------
1  APR-1-2017
2  JAN-1-2017
3  JULY-5-2016
4  DEC-6-2015
5  FEB-3-2017
5  JAN-1-2018
1  JAN-1-2018

我希望能够选择任何特定的日期或日期范围,这将为我提供该日期的ID。然后我想在过去365天选择这些ID的计数。

我能够让查询正常工作。但唯一的问题是我使用的应用程序并不理解WITH Temp Table。

是否有其他方法可以编写此查询?

WITH list_to_compare as (select distinct(ID) AS LASTWEEKOUT 
                        from TABLEA 
                        WHERE TIMESTAMP >= SYSDATE -1)
SELECT TABLEA.ID,count(*)
    from list_to_compare LTC 
        LEFT OUTER join TABLEA 
            on LTC.lastweekout = TABLEA.ID
WHERE TABLEA.TIMESTAMP >= SYSDATE - 365 
group by TABLEA.ID
having COUNT(*) > 12;

4 个答案:

答案 0 :(得分:3)

您想要为某些ID选择数据。出于某种原因,您认为必须将这些ID加入到您的表中,但实际上它只是标准,并且更好地属于WHERE子句。 (你甚至伪外连接表到ID,虽然从日期知道你总是匹配。)

以下是WHERE子句中放置标准的查询:

select id, count(*)
from tablea
where id in (select id from tablea where timestamp >= sysdate - 1)
and timestamp >= sysdate - 365 
group by id
having count(*) > 12;

但是当你正在聚合时,你甚至可以在HAVING子句中查找所有条件,因此只需从表中选择一次:

select id, count(*)
from tablea
where timestamp >= sysdate - 365 
group by id
having count(*) > 12
and count(case when timestamp >= sysdate - 1 then 1 end) > 0;

答案 1 :(得分:1)

我不明白你需要什么,但是你可以用内部选择替换SELECT Table1.ID,count(*) from (select distinct(ID) AS LASTWEEKOUT from Table1) LTC LEFT OUTER join Table1 on LTC.lastweekout = Table1.ID WHERE Table1.STARTDATE >= SYSDATE - 365 group by Table1.ID having COUNT(*) > 12;

x

答案 2 :(得分:1)

只需移动WITH因子子句" s" table"进入内联视图:

SELECT TABLEA.ID,count(*)
    from (select distinct(ID) AS LASTWEEKOUT 
          from TABLEA 
          WHERE TIMESTAMP >= SYSDATE -1) LTC
    LEFT OUTER join TABLEA  on LTC.lastweekout = TABLEA.ID
WHERE TABLEA.TIMESTAMP >= SYSDATE - 365 
group by TABLEA.ID
having COUNT(*) > 12;

答案 3 :(得分:1)

  

...我正在使用的应用程序不了解Temp Table。

很有可能它不喜欢外部查询以WITH开头 - 你可以通过用select * from (…)包装每个查询来解决这个问题:

with w as (select * from dual)
select * from w;
| DUMMY |
| :---- |
| X     |
select *
from ( with w as (select * from dual)
       select * from w );
| DUMMY |
| :---- |
| X     |

dbfiddle here