# Show data for last X days

**URL:** <https://meta.discourse.org/t/show-data-for-last-x-days/215810>\
**Category:** Data & reporting\
**Tags:** sql-query\
**Created:** [January 24, 2022, 1:59pm UTC](https://meta.discourse.org/t/show-data-for-last-x-days/215810 "2022-01-24T13:59:55Z")\
**Posts on this page:** 4\
**Page:** 1

## AI-generated summary

In the 'Data & reporting' category, user [Amine_Akkar](/t/-/215810/1) sought assistance with a SQL query to generate a report of user visits over the last 30 days. They initially attempted to use `max(visited_at)` with a `CAST` condition but encountered issues. [Falco](/t/-/215810/2) suggested an alternative approach using `COUNT(*)` grouped by `user_id` and filtered by `visited_at > CURRENT_DATE - 30`. [Amine_Akkar](/t/-/215810/3) confirmed that Falco's solution worked correctly.

<div class="post-metadata">

**Author:** ![Amine\_Akkar](https://avatars.discourse-cdn.com/v4/letter/a/dfb087/32.png) [@Amine\_Akkar](https://meta.discourse.org/u/Amine_Akkar)\
**Post date:** [January 24, 2022, 1:59pm UTC](https://meta.discourse.org/t/show-data-for-last-x-days/215810/1 "2022-01-24T13:59:55Z")

</div>

Hello  
I’m trying to run a report how shown the visits during the last 30 days, so I used this query but apparently, it’s wrong :

```plaintext
select distinct user_id, max(visited_at) as visited_at from user_visits
WHERE CAST(visited_at AS DATE) >= GETDATE() -30
group by user_id

```

I tested also this condition

`WHERE CAST(visite d_at AS DATE) >= CAST(GETDATE() -30 AS DATE)`

is it possible to have this kind of conditions ?  
Thank you

---

<div class="post-metadata">

**Author:** ![Falco](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/falco/32/179432_2.png) [@Falco](https://meta.discourse.org/u/Falco)\
**Post date:** [January 24, 2022, 2:48pm UTC](https://meta.discourse.org/t/show-data-for-last-x-days/215810/2 "2022-01-24T14:48:06Z")

</div>

> [@Amine\_Akkar](#):
>
> a report how shown the visits during the last 30 days

Try

```sql
SELECT
  user_id,
  COUNT(*) AS visits
FROM user_visits
WHERE visited_at > CURRENT_DATE - 30
GROUP BY 1
ORDER BY 2 DESC

```

---

<div class="post-metadata">

**Author:** ![Amine\_Akkar](https://avatars.discourse-cdn.com/v4/letter/a/dfb087/32.png) [@Amine\_Akkar](https://meta.discourse.org/u/Amine_Akkar)\
**Post date:** [January 24, 2022, 2:52pm UTC](https://meta.discourse.org/t/show-data-for-last-x-days/215810/3 "2022-01-24T14:52:34Z")

</div>

thank you @Falco , it works fine

---

<div class="post-metadata">

**Author:** ![system](https://sea3.discourse-cdn.com/meta/user_avatar/meta.discourse.org/system/32/443519_2.png) [@system](https://meta.discourse.org/u/system)\
**Post date:** [February 23, 2022, 2:53pm UTC](https://meta.discourse.org/t/show-data-for-last-x-days/215810/4 "2022-02-23T14:53:05Z")

</div>

Closed on February 23, 2022, 2:53pm UTC

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.
