% change of 2 time period calculations in SQL (GBQ) [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 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

Related

How to retrieve the minimum date having 3 columns (day), (month) and (year) with RSQLite? [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 am working with SQL in R. I want to get the minimum date by choosing the minimum value of the column 'day;, the minimum value of the column 'month' and the minimum value of the column 'year'.
I have tried this by the following code:
dbGetQuery(db, "SELECT day, month, year
FROM surveys
WHERE year = (SELECT MIN(year) FROM surveys);")
But my output is not one value, how can I get one value in my output and not a list of values?
Right now your query returns rows on the minimum year, not minimum date. Consider generating a date column by concatenating the date parts to identify minimum:
sql = "WITH sub AS (
SELECT day, month, year
, DATE(year || '-' ||
CASE
WHEN length(month)=1
THEN '0' || month
ELSE month
END || '-' ||
CASE
WHEN length(day)=1
THEN '0' || day
ELSE day
END) AS [date]
FROM surveys
)
SELECT DISTINCT day, month, year, [date]
FROM sub
WHERE [date] = (SELECT MIN([date]) FROM sub)"
dbGetQuery(db, sql)
Online Demo
Using the test data shown we order it by year, month and day and select the first row of the sorted table.
library(sqldf)
surveys <- data.frame(year = 2001:2005, month = 5:1, day = 1:5)
sqldf("select day, month, year from surveys order by year, month, day limit 1")
## day month year
## 1 1 5 2001

How to get last (n) dates by sql query? [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
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

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.

COUNT function use [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a requirement, there is a table CR. Type is a field here. Now it has values like A,B,C. I need separate counts for CR records having type A in month Jan,Feb,...Dec 2013.Same for Type B and C in SQL SERVER 2008. A, B, C will be column headers and count of each for a month-year combination comes under it.
Can someone help me here?
You need google first before asking this...
SELECT * FROM
(SELECT type, datepart(mm, date) month, count(1) cn
FROM CR
WHERE datepart(yyyy, date) = '2013'
GROUP BY type, datepart(mm, date)
) AS t
PIVOT(MIN(cn) FOR type IN ([A], [B], [C])) AS m
Assuming that the CR table have a datetime field called dat you can GROUP BY MONTH in this way :
SELECT DATEPART(Month, dat) AS month, Type
FROM CR
WHERE DATEPART(Year, dat) = 2013
GROUP BY Type , DATEPART(Year, dat), DATEPART(Month, dat)

Query related to month and year [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have a table which contains Year and Month as columns like below:-
Id Year Month Value
1 2012 12 100
2 2013 1 200
3 2013 2 300
4 2013 12 200
5 2012 11 200
I want to create a query which gives me values with (year >= 2012 and month >= 12) and also (year =< 2013 and month =< 12) i.e. It should give me Id 1, 2, 3, 4.
EDIT
This is just an example to demonstrate the behavior.
The months and Year might vary. So please create an answer that suits the condition for any year and any month that are passed.
How can I create a query with the following condition?
Regards
Vishal
This should get you what you want
SELECT id
FROM YourTable
WHERE (Year = '2013' OR (Year = '2012' AND Month = '12'))
I hope I've understood your conditions now ("i want 2012 12 month abd 2013 1 to 12 month data"):
SELECT Id FROM TableName WHERE (Year = 2012 AND Month = 12) OR (Year = 2013) ORDER BY Id
This is assuming there can't be a month > 12 or < 1 ;-)
declare #YearFrom int, #YearTo int, #MonthFrom int, #MonthTo int
set #YearFrom = 2012
set #YearTo = 2013
set #MonthFrom = 12
set #MonthTo = 12
select ID, YEAR, MONTH, Value
from [yourtable]
WHERE (year = #yearfrom AND month >= #monthfrom or year > #yearfrom)
AND (year = #yearto AND month <= #monthto or year < #yearto)
I think the easiest way is to convert the columns to a bigger integer (or string). Assuming the values are integers:
select id
from table
where year*100+month between 201212 and 201312;
edit based on comment
For a given #yearIN
select * from table
where (year = #yearIN and month != 12) or (year = (#yearIN-1) and month = 12)
I think this is what you want
select * from table
where (year = 2013 and month != 12) or (year = 2012 and month = 12)
I think this makes the logic of what you are looking for clearer -- I expect you don't want the last month of 2011