SQL - 从表中选择,然后从表中选择计数

问题描述 投票:0回答:4

我有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临时表。

有没有其他方法来编写此查询?

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;
sql oracle select count
4个回答
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
投票

我不明白你需要什么,但你可以用内部选择替换WITH

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;

1
投票

只需将WITH factoring子句的“表”移动到内联视图中:

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;

1
投票

...我正在使用的应用程序不理解临时表。

很有可能它只是不喜欢以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

© www.soinside.com 2019 - 2024. All rights reserved.