Getting derived column from database | SQL query | DB2 SystemDate - sql

My table is PRODUCTINFO:
Column name : product_name | launch_date
Sample Date : product1 2017-01-20
I need a SQL query to decide if the product is newly launched or not.
Business rule :
if (launch_date - currentdate < 0 && currentdate - launch_date < 90)
newly_launched = 'YES'
else
newly_launched = 'NO'
where currentdate is today's date.
SQL query I am witting is like :
SELECT launch_date, X as newly_launched
FROM PRODUCTINFO
WHERE product_name = 'product1'
I am not able to figure out correct replacement of 'X' in my query for desired result.
Problem I am facing is using currentdate and if else block in my query
Please help.
One way to get currentdate in DB2 using following query :
SELECT VARCHAR_FORMAT(CURRENT TIMESTAMP, 'YYYYMMDD')
FROM SYSIBM.SYSDUMMY1
Still not sure how to use this with my if else scenario.
Answer here don't solve my problem as this scenario is if-else based.

use TIMESTAMPDIFF with 16 as first parameter for count number days between 2 timestamps, for more detail look here
try this
select launch_date,
case when TIMESTAMPDIFF( 16, cast(cast(launch_date as timestamp) - current timestamp as char(22))) >0 and
TIMESTAMPDIFF( 16, cast(cast(launch_date as timestamp) - current timestamp as char(22))) <90 then 'YES' else 'NO' end newly
from PRODUCTINFO
WHERE product_name = 'product1'

simply use datediff function in a case syntax, I hope it could help!
SELECT launch_date,
case
when DATEDIFF(day,launch_date,getdate()) BETWEEN 0 AND 90 then 'YES'
else 'NO'
end AS newly_launched
FROM PRODUCTINFO
WHERE product_name = 'product1'
in case you want to do it for all your records:
SELECT launch_date,
case
when DATEDIFF(day,launch_date,getdate()) BETWEEN 0 AND 90 then 'YES'
else 'NO'
end AS newly_launched
FROM PRODUCTINFO

Related

MIN and MAX in case expression

I want to get MIN or Max date base on condition(s.REQUIRED_DATE >= trunc(SYSDATE-1)).
Below is my query.
It gives me error ORA-00937: not a single-group group function
SELECT
case when s.REQUIRED_DATE >= trunc(SYSDATE-1) then
MIN(required_date)
else
MAX(required_date)
end required_date
FROM anytable s
WHERE s.abc = 'hhj';
How can I achieve this?
Query must return 17-AUG-2020 for 'hhj' and 15-AUG-2020 for 'bbj'
id abc required_date
1 hhj 14-Aug-2020
2 hhj 17-AUG-2020
3 hhj 19-AUG-2020
3 bbj 15-AUG-2020
4 bbj 12-AUG-2020
I can adopt any other approach also if required.
Please suggest
It seems, for a particular abc you want to get:
the required_date nearest to and past the date yesterday if there's a required_date past the date yesterday, or
get the latest required_date if they don't pass the date yesterday.
If so, this query may be what you wanted:
select
case when max(required_date)>=trunc(sysdate-1) then
min(case when required_date>=trunc(sysdate-1) then required_date end)
else max(required_date)
end required_date
from anytable s
where s.abc='hhj';
Use Aggregate function on whole case statement and for this you have to use two case statements.
SELECT
MIN(case when s.ENTRY_DATE >= trunc(SYSDATE-1) then
ENTRY_DATE
end) MIN_required_date,
MAX(case when s.ENTRY_DATE < trunc(SYSDATE-1) then
ENTRY_DATE
end) MAX_required_date
FROM DATE_TEST s

Using SUM SEC_TO_TIME in MariaDB

Reference from How to sum time using mysql
I want to SUM Field LogsFormatted.Late Every month with query :
SELECT
SUM(CASE
WHEN MONTH (LogsFormatted.DateIn) = 1
THEN SEC_TO_TIME( SUM( TIME_TO_SEC(LogsFormatted.Late)))
ELSE 0 END
) AS '1'
FROM
HrAttLogsFormatted AS LogsFormatted
But the result is
1111 - Invalid use of group function
Where is the problem with the query? resulting in an error output.. Thank you in advance
[EDIT-SOLVED] It's Solved with simply apply
Change format SUM at the beginning of the query
SEC_TO_TIME(SUM(
CASE WHEN MONTH(LogsFormatted.DateIn) = 1 THEN
TIME_TO_SEC(LogsFormatted.Late) END)
) AS '1'
You don't need to call the sum() so many times. You can also move the case condition to the WHERE clause:
SELECT SUM(TIME_TO_SEC(lf.Late))
FROM HrAttLogsFormatted lf
WHERE MONTH(lf.DateIn) = 1 ;
If you want conditional aggregation, then do:
SELECT SUM(CASE WHEN MONTH(lf.DateIn) = 1 THEN TIME_TO_SEC(lf.Late) END)
FROM HrAttLogsFormatted lf;

SSRS Report with date range with group by

I have a table FinalQuote in SQL Server with these columns:
Q_hub_from : Perth, Burnie, Sydney etc.
Q_hub_to : Perth, Burnie, Sydney etc.
FinalMargin : 400, 500, 650 etc.
processed_at : Date Time
BookedYN : Yes/No.
I want to create a SSRS report which will show the average value of FinalMargin for all the rows from a specific Q_hub_from to specific Q_hub_to. Also wanna show average margin in two columns: one contain average of rows where BookedYN is 'YES' and other contain average of rows where BookedYN is 'NO'. It is working fine and display required result when I specify a date range(for processed_at) in query.
My query so far is:
SELECT
Q_hub_from, Q_hub_to,
ROUND(AVG(FinalMargin), 0) AS Margin,
COUNT(*) AS NoOfQuotesDone,
COUNT(CASE BookedYN WHEN 'Yes' THEN 1 ELSE NULL END) AS NoOfQuotesBooked,
ROUND(AVG(CASE BookedYN WHEN 'No' THEN FinalMargin ELSE NULL END), 0) AS MarginWhenNotBooked,
ROUND(AVG(CASE BookedYN WHEN 'Yes' THEN FinalMargin ELSE NULL END), 0) AS MarginWhenBooked
FROM
FinalQuote
WHERE
Q_hub_from <> ''
AND Q_hub_from IS NOT NULL
--AND CAST(processed_at as date) BETWEEN '2018-08-01' AND '2018-10-10'
AND CAST(processed_at AS DATE) BETWEEN DATEADD(day, -10, GETDATE()) AND GETDATE()
GROUP BY
Q_hub_from, Q_hub_to
ORDER BY
Q_hub_from ASC
This query produces this output:
But I want date range to be selected by user, so I added StartDate and EndDate parameters. My processed_at column only mentioned in the WHERE clause, not in the select statement, so I get this error:
[rsMissingFieldInDataSet] and [rsErrorReadingDataSetField]
When I add processed_at field in DataSet and in GROUP BY clause then it is working (although still displays previous error) but now result is not expected. It shows 2 rows for same Q_hub_from and Q_hub_to.
Query:
SELECT Q_hub_from, Q_hub_to, processed_at, ROUND(AVG(FinalMargin),0) AS Margin,
COUNT(*) AS NoOfQuotesDone, COUNT(case BookedYN when 'Yes' then 1 else null end) AS NoOfQuotesBooked,
ROUND(AVG(case BookedYN when 'No' then FinalMargin else null end),0) AS MarginWhenNotBooked, ROUND(AVG(case BookedYN when 'Yes' then FinalMargin else null end),0) AS MarginWhenBooked
FROM FinalQuote
WHERE Q_hub_from <> '' AND Q_hub_from IS NOT NULL
AND processed_at between #StartDate AND #EndDate
GROUP BY Q_hub_from, Q_hub_to, processed_at
ORDER BY Q_hub_from ASC
Output:
If anyone can help me in achieving the required result that only show 1 row for same Q_hub_from to Q-hub_to within specific date range(i.e. processed_at between StartDate and EndDate) that will be of great help. I don't wanna display processed_at column. I know I am doing something wrong as Its my first time with SSRS.
Feel free to ask if you want to know more. Any help will be appreciated! Thanks.
If you have not set the values for parametes then try to assign some values to parameters and make sure parameter type is Date.
You can do it like this,
create a dataset and put this query select DATEADD(day, -10, GETDATE()) AS StartDate, GETDATE() AS EndDate
Use this dataset for your both the parameters only in default values section. Don't add it in available values section.
Suggestion 1: AND cast( processed_at as date) between #StartDate AND #EndDate . As you need to make sure how this column is stored in the tables. If it is DateTime then do an implicit cast to date.
Suggestion 2: on the SSRS make sure you can see your 2 params are params. IF you do then DO NOT SET any values for them. See if you can pick any random range and report renders.
Suggestion 3: if you have to put default values make sure they are either query or best case stored proc generated (sometime like usp_report_params_defaultDateRange). You will give this for default date range. Also type will be date and not int, varchar, etc.
Suggestion 4: If above fail trying building a query and just hardcoding the values so something like Select '2000-01-01' as Q_hub_from, '2001-01-01' as Q_hub_to from table name where cast( processed_at as date) between #StartDate AND #EndDate and see if it works. Add 1 column at a time and anchor to report and see if it gives you error. (NOTE YOU HAVE TO DELETE .DATA file from your local Bin folder after each local successful run)

Case Function in Oracle - wrong return

I have an table with these fields:
id,
quarter,
description,
id_school.
These table have this data:
ID | quarter | description
12 A 1 YEAR
12 S 1 Year
12 A DONE
I want to get the serie_school based on the below query:
select NVL(
case
WHEN quarter = 'S' AND
(UPPER(description ) LIKE 'DONE' OR
UPPER(description ) LIKE '%YEAR' OR
UPPER(description ) LIKE 'LANGUAGE') THEN -1
WHEN quarter = 'A' AND
(UPPER(description ) LIKE 'DONE' OR
UPPER(description ) LIKE '%QUARTER' OR
UPPER(description ) LIKE '%STEP' OR
UPPER(description ) LIKE 'LANGUAGE') THEN -1
WHEN quarter = 'T' THEN -1
ELSE -1
end, -1) nvl_return from test
The return of this on my query is:
ID | quarter | description | nvl_return
12 A 1 YEAR 1
12 S 1 Year 1 *- (this column has the wrong answer)*
12 A DONE -1
The answer of line 2 is wrong, because the QUARTER field is 'S' and the description field have 'year', so it needs to be -1, but in Oracle is returning 1.
Is there anyone who can help me with this?
Thanks in advance
Alexandre,
Examine your statement, where I have added "<======" to point out the various possible amounts for this column.
select NVL(
case
WHEN quarter = 'S' AND
(UPPER(description ) LIKE 'DONE' OR
UPPER(description ) LIKE '%YEAR' OR
UPPER(description ) LIKE 'LANGUAGE') THEN -1<=======
WHEN quarter = 'A' AND
(UPPER(description ) LIKE 'DONE' OR
UPPER(description ) LIKE '%QUARTER' OR
UPPER(description ) LIKE '%STEP' OR
UPPER(description ) LIKE 'LANGUAGE') THEN -1<======
WHEN quarter = 'T' THEN -1 <======
ELSE -1 <=======
end, -1 <-this will never happen) nvl_return from test
You return "-1" in every single case. "-1" is the only value returned, by the only column returned in your query.
So when you say the results are:
ID | quarter | description | nvl_return
12 A 1 YEAR 1
12 S 1 Year 1 *- (this column has the wrong answer)*
12 A DONE -1
Unfortunately, your query cannot produce the results you've stated.
Try creating a SQL fiddle, to explain the issue. SQL Fiddle

SQLite strftime function issue with timezone

I have following table structure where are saved some dates:
I tried to group results by hours using strftime sqlite function, but i found the problem if datetime value is stored like:
2015-01-21 11:49:16CET
In this case is value not converted. But if i erased "CET" value to have something like this:
2015-01-21 10:44:09
I got the correct result.
Query:
SELECT strftime('%H', dc.date) as hr,
COUNT(*) AS DIALS_CNT,
SUM(CASE WHEN dc.call_result = 'APPT' THEN 1 ELSE 0 END) AS APPT_CNT,
SUM(CASE WHEN dc.call_result = 'CONV_NO_APPT' THEN 1 ELSE 0 END) AS CONVERS_CNT,
SUM(CASE WHEN dc.call_result = 'CANNOT_REACH' THEN 1 ELSE 0 END) AS CANNOT_REACH_CNT
FROM dialed_calls dc
GROUP BY strftime('%H', dc.date);
Should i remove timezone from date column or how can i solve it please?
Many thanks for any advice.