How to get last (n) dates by sql query? [closed] - sql

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
For example DECLARE #a = 10;
Required output be like:
1) 16/5/2020
2) 15/5/2020
3) 14/5/2020
4) 13/5/2020
5) 12/5/2020
6) 11/5/2020
7) 10/5/2020
8) 9/5/2020
9) 8/5/2020
10) 7/5/2020
If Declare #b = 5 then get last five days of dates in output.

Snowflake:
SELECT DATEADD(DAY, -SEQ4(), CURRENT_DATE()) AS generated_date
FROM TABLE(GENERATOR(ROWCOUNT=>10))
ORDER BY generated_date desc;
SEQn() functions are not guaranteed to be gap free, so you need to use ROW_NUMBER()
WITH tally AS (
SELECT ROW_NUMBER() OVER(ORDER BY SEQ4()) AS rn
FROM TABLE(GENERATOR(ROWCOUNT=>10))
)
SELECT DATEADD(DAY, -rn, CURRENT_DATE()) AS generated_date
FROM tally
ORDER BY generated_date

Related

How to Improve this query for PostgreSQL [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
select SUM(count.counts), CountMostUtilizedApps
from
( (select count(*) from performance.apps WHERE start_date >= '2021-02-06 00:00:00'
AND start_date <= '2021-02-09 00:00:00' and dh.parent_id in ('1234','8910') and group_id in ('4567','1112') group by crashes order by crashes desc limit 5) counts
(select count(*) from performance.apps WHERE start_date >= '2021-02-06 00:00:00'
AND start_date <= '2021-02-09 00:00:00' and parent_id in ('1234','8910') and group_id in ('4567','1112') order by AppTime limit 10) CountMostUtilizedApps
)
The most important thing is to properly write code, even if this is SQL script and ask question in question content, not only in title.
Like in following refcatored SQL query (from yours question):
SELECT
SUM(count.counts)
,CountMostUtilizedApps
FROM
SELECT
SUM(count.counts)
,CountMostUtilizedApps
FROM
(
(
SELECT count(*) from performance.apps
WHERE
start_date >= '2021-02-06 00:00:00'
AND start_date <= '2021-02-09 00:00:00'
AND dh.parent_id IN ('1234','8910')
AND group_id IN ('4567','1112')
GROUP BY
crashes
ORDER BY
crashes desc limit 5
) counts
(
SELECT
count(*)
FROM
performance.apps
WHERE
start_date >= '2021-02-06 00:00:00'
AND start_date <= '2021-02-09 00:00:00'
AND parent_id IN ('1234','8910')
AND group_id IN ('4567','1112')
ORDER BY
AppTime limit 10
) CountMostUtilizedApps
)
Asking: How to Improve this following query for PostgreSQL ?
Is not enough. Be more specific. What you exactly mean ?
I'm not PostgreSQL expert, and more important thing as any other here you must to give more details, because nobody here do not know what your database contains .
As I said I'm not PostgreSQL expert but for my first look your's SQL Query should'nt works at all...Isn't it true ?

Sum of a column that is a SUM [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 2 years ago.
Improve this question
I have a query that I inherited:
SELECT SUM(Credit) AS Total, Account, Date
FROM
(
SELECT DISTINCT
CONVERT(char(10), dbo.vCustomer_Invoice.Accounting_Distribution__Document_Date, 101) AS Date
, dbo.vCustomer_Invoice.Accounting_Distribution__Amount_Credit AS "Credit"
, dbo.vCustomer_Invoice.Accounting_Distribution__GL_Account AS "Account"
FROM dbo.vCustomer_Invoice
WHERE CONVERT(char(10), dbo.vCustomer_Invoice.Accounting_Distribution__Document_Date, 101) = '11/03/2020' AND (dbo.vCustomer_Invoice.Accounting_Distribution__GL_Account LIKE '4000%' OR dbo.vCustomer_Invoice.Accounting_Distribution__GL_Account LIKE '4100-700-%')
)
AS D
Group By Account, Date;
This gives me a total by each GL_Account for a date. I'd like to now add a column that Sums by Date. I have in the past used a UNION ALL but I can't get that to work with this query configuration.
Any help would be appreciated.
You can use SUM() window function for this new column:
SELECT SUM(Credit) AS Total,
Account,
Date,
SUM(SUM(Credit)) OVER (PARTITION BY Date) AS Total_By_Date
FROM (
SELECT DISTINCT
CONVERT(CHAR(10), Accounting_Distribution__Document_Date,101) AS Date,
Accounting_Distribution__Amount_Credit AS Credit,
Accounting_Distribution__GL_Account AS Account
FROM dbo.vCustomer_Invoice
WHERE CONVERT(CHAR(10), Accounting_Distribution__Document_Date, 101) = '11/03/2020'
AND (Accounting_Distribution__GL_Account LIKE '4000%' OR Accounting_Distribution__GL_Account LIKE '4100-700-%')
) AS D
GROUP BY Account, Date;

% change of 2 time period calculations in SQL (GBQ) [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
Currently have multiple calculations similar to this:
SELECT SUM(A)/COUNT(B) AS CALCULATION
FROM TABLE
WHERE YEAR = 2019
But I want to find the percent change between Year 2019 and 2018,
like (Calculation1/Calculation2-1) where calc1 is 2019 and calc2 is 2018.
Is the best way a temp table or a subquery? What would be some base code to accomplish analysis?
You can use conditional aggregation. I'm not sure exactly what calculation you want, but something like this:
SELECT (SUM(CASE WHEN YEAR = 2019 THEN A END) / SUM(CASE WHEN YEAR = 2018 THEN A) END) - 1 AS CALCULATION
FROM TABLE
WHERE YEAR IN (2018, 2019)
Below is for BigQuery Standard SQL
#standardSQL
SELECT
(SUM(IF(year = 2019, A, 0)) / COUNT(IF(year = 2019, B, NULL))) /
(SUM(IF(year = 2018, A, 0)) / COUNT(IF(year = 2018, B, NULL))) - 1 AS CALCULATION
FROM `project.dataset.table`
WHERE year IN (2018, 2019)
Using IF. A little bit ugly but a more generalized version:
with yearlyset as (
select
year,
lag(year) over(order by 1) lastyear,
coalesce(lag(calculation) over(order by 1), 0) lastyearcalculation,
calculation from (
select year, sum(a)/count(b) as calculation
from `dataset.table`
group by 1
)
)
select
year,
if(
year=2019 and lastyear=2018,
calculation/lastyearcalculation-1,
if(
coalesce(lastyearcalculation, 0) = 0,
0.0,
calculation/lastyearcalculation
)
) as percent_change
from yearlyset

SQL Server trigger based on Datetime [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I need to create a trigger in SQL Server 2017 that will fire on INSERT and work off the CreatedDate column of my table.
The CreatedDate is of this format: 2017-09-21 07:15:59.883
What I want to do is check the time of the CreatedDate column and if it is between 7 and 8 I need to insert a value into a Notes column, if it is between 15 and 16 I need to insert another, if it is between 23 and 24 I need to insert another.
I am particularly stuck at the WHERE clause that I need to check the hour for. Not sure how to formulate this.
assuming your CreatedDate is datetime and not string
use datepart to checks for createdate hour and update the Notes column accordingly
UPDATE t
SET Notes = 'a value'
FROM inserted i
INNER JOIN mytable t ON i.pk = t.pk
WHERE datepart(hour, CreateDate) in (7, 8)
EDIT :
UPDATE t
SET Notes = case when datepart(hour, CreateDate) in ( 7, 8) then 'a value'
when datepart(hour, CreateDate) in (15, 16) then 'another value'
end
FROM inserted i
INNER JOIN mytable t ON i.pk = t.pk
WHERE datepart(hour, CreateDate) in (7, 8, 15, 16)
See datepart
where case when DATEPART ( HOUR, datetimeField ) =7 then someValue
case when DATEPART ( HOUR, datetimeField ) =15 then SomeOtherValue
case when DATEPART ( HOUR, datetimeField ) =23 then AnotherDiffetentValue
end
You can use DATEPART: https://learn.microsoft.com/en-us/sql/t-sql/functions/datepart-transact-sql
and CASE: https://learn.microsoft.com/en-us/sql/t-sql/language-elements/case-transact-sql

check expiry cards [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I have a table to stores expiry dates of credit cards, below is the sample schema for table.
ExpiryDate Varchar(10)
Sample Data in Table is as follows:-
'08/10'
'09/11'
'08/16'
'10/17'
how can i find out if a card's date is expired?
I am not sure what you are expected, but You can use string manipulation with substring to get records those are not expired
Select *
FROM supportContacts
WHERE LEFT(ExpiryDate,2) >= MONTH(GETDATE()) AND RIGHT(ExpiryDate,2) >= RIGHT(YEAR(GETDATE()),2)
If you want expired card list then use this
Select *
FROM supportContacts
WHERE LEFT(ExpiryDate,2) < MONTH(GETDATE()) AND RIGHT(ExpiryDate,2) <= RIGHT(YEAR(GETDATE()),2)
SQL DEMO
With such an awful data structure you are forced to kludge this together. Here is one way of doing it.
with BadData as
(
select '08/10' as SemiDate union all
select '09/11' union all
select '08/16' union all
select '10/17'
)
select *
from BadData
where cast(replace(STUFF(SemiDate, 4, 0, '01-20'), '/', '-') as DATE) < CAST(getdate() as DATE)
If you stored the ExpirationDate as a date instead of a string this would be simple. I sure hope you aren't storing the credit card number alongside this.
select *
from billinginfo
where substring(expirydate,1,charindex('/',expirydate)-1) < month(getdate())
and '20'+ substring(expirydate,charindex('/',expirydate)+1, 2) <= year(getdate())
You can try this.
You want something like this:
select * from BillingInfo
where
cast(left(expiryDate, 2) as int) --take the month portion of the expiry date
< select datepart(mm, getdate()) --expiry month must be before current month
and
cast(right(expiryDate, 2) as int) --take the year portion of the expiry date
<= select datepart(yy, getdate()) % 1000 --expiry year must also be during or before current year
The % 1000 converts the year to two-digit format.
I guess you want this:
SELECT TOP 4 *
FROM BillingInfo
WHERE ExpiryDate in ('08/10','09/11','08/16','10/17')
This will find you the 4 items with those dates.