In IF statement with dates see whether a NULL exists - sql

I have this query and i see if the AUD_CloseDate is > than todays date. Now i imagine these would be a NULL somewhere in AUD_CloseDate so in this statement i also want to check if there is a NULL value in AUD_CloseDate and if there is assign value 1900\01\01
SELECT ([Target Status] + '' + CAST(COUNT(*) AS NVARCHAR(255)) + ' of ' + CAST(#Total AS NVARCHAR(255))) AS TargetStatus, CAST(COUNT(*) AS FLOAT)/CAST(#Total AS FLOAT) AS [Count]
FROM (
SELECT CASE WHEN CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,t2.AUD_CloseDate), 101)) < CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,GETDATE()), 101))AND t1.[Status] in ('Open','Closed')
THEN 'Over Due: '
ELSE 'On Time: ' END AS [Target Status]
FROM #tmp1 t1 INNER JOIN dbo.Audit t2
ON t1.AUD_ID = t2.AUD_ID
WHERE t2.AUD_Deleted = 0
AND t2.AUD_LeadAuditor IN (SELECT ID FROM [dbo].[fx_SplitCommaSeperatedValues] (#LeadAssessor))
AND t2.AUD_Year = #Year
AND AUD_Quarter IN (SELECT ID FROM [dbo].[fx_SplitCommaSeperatedValues] (#Quarter)))DER

COALESCE is ANSI-compliant. Same syntax as ISNULL: COALESCE(t2.AUD_CloseDate,'19000101')

Why about a ISNULL() statement ?
ISNULL(t2.AUD_CloseDate,'19000101')
In you example :
SELECT ([Target Status] + '' + CAST(COUNT(*) AS NVARCHAR(255)) + ' of ' + CAST(#Total AS NVARCHAR(255))) AS TargetStatus, CAST(COUNT(*) AS FLOAT)/CAST(#Total AS FLOAT) AS [Count]
FROM (
SELECT CASE WHEN CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,ISNULL(t2.AUD_CloseDate,'19000101')), 101)) < CONVERT(DATETIME,CONVERT(CHAR(10),DATEADD(DAY,0,GETDATE()), 101))AND t1.[Status] in ('Open','Closed')
THEN 'Over Due: '
ELSE 'On Time: ' END AS [Target Status]
FROM #tmp1 t1 INNER JOIN dbo.Audit t2
ON t1.AUD_ID = t2.AUD_ID
WHERE t2.AUD_Deleted = 0
AND t2.AUD_LeadAuditor IN (SELECT ID FROM [dbo].[fx_SplitCommaSeperatedValues] (#LeadAssessor))
AND t2.AUD_Year = #Year
AND AUD_Quarter IN (SELECT ID FROM [dbo].[fx_SplitCommaSeperatedValues] (#Quarter)))DER

Use ISNULL function
ISNULL(AUD_CloseDate, '1900-01-01')
You are also:
adding 0 days to date
casting it to char(10)
, then casting again to date... Why?
You can achieve the same result withou these conversions, like this example:
SELECT
CASE
WHEN ISNULL(#a, '2014-01-29 13:50') < GETDATE()
THEN 'Over Due: '
ELSE 'On Time: '
END
Results 'Over due:'
SELECT
CASE
WHEN ISNULL(#a, '2014-01-29 15:00') < GETDATE()
THEN 'Over Due: '
ELSE 'On Time: '
END
Results 'On Time:'
** Now is 13:55 :)

Related

Trying to convert this SQL query to athena query

Trying to convert this to Athena query special the case statement bit
select
RegDate,
COALESCE(cast(convert(varchar(7), RegDate, 126) as varchar(7)), NULL ) as [RegMonthYear]
,DATEPART(month, RegDate) as RegMonth
,DATEPART(year, RegDate) as RegYear
,code
,case
when cast(year(RegDate)as nvarchar)
+case when len(cast(month(RegDate) as nvarchar)) = 1 then '0'+cast(month(RegDate) as nvarchar)
else cast(month(RegDate) as nvarchar)
end < '20'+code+'01'
then 'Jan'
when cast(year(RegDate)as nvarchar)
+case when len(cast(month(RegDate) as nvarchar)) = 1 then '0'+cast(month(RegDate) as nvarchar)
else cast(month(RegDate) as nvarchar)
end > '20'+code+'12'
then 'Dec'
else Convert(char(3), RegDate,0)
end EditionMonth
,case
when cast(year(RegDate)as nvarchar)
+case when len(cast(month(RegDate) as nvarchar)) = 1 then '0'+cast(month(RegDate) as nvarchar)
else cast(month(RegDate) as nvarchar) end < '20'+code+'01' then 1
when cast(year(RegDate)as nvarchar)
+case when len(cast(month(RegDate) as nvarchar)) = 1 then '0'+cast(month(RegDate) as nvarchar)
else cast(month(RegDate) as nvarchar)
end > '20'+code+'12' then 12
else DATEPART(m,RegDate)
end EditionMonthNumber
from Details

How to write a loop for such sql query

I need to write such query:
SELECT CAST (date_time_column AS DATE) as 'Date',
AVG(CASE WHEN FORMAT(date_time_column, 'HH:mm') = '00:00' then my_values ELSE NULL end) as '00:00',
........
AVG(CASE WHEN FORMAT(date_time_column, 'HH:mm') = '23:59' then my_values ELSE NULL end) as '23:59'
FROM table
where date_time_column > '2021-08-12'
GROUP BY CAST (date_time_column AS DATE)
What is a way to avoid writing 1440 lines in a query?
Try the below method (Change the variables to match your table and field)
/*Generate all minutes in a day in a string variable*/
Declare #timeRange varchar(max)=null
declare #startdate Datetime='2021-08-12 00:00';
; WITH cte AS
(
SELECT 1 i, #startdate AS resultDate
UNION ALL
SELECT i + 1, DATEADD(minute, i, #startdate )
FROM cte
WHERE DATEADD(minute, i, #startdate ) < DateAdd(day,1,#startdate)
)
SELECT #timeRange=Coalesce(#timeRange +',' + '['+Format(resultDate,'HH:mm')+']','['+Format(resultDate,'HH:mm')+']') FROM cte
OPTION (MAXRECURSION 2000);
/* (Change These variables to match your table & fields */
declare #filterQuery varchar(300)=' where {date_time_column}>''2021-01-01''';
declare #dateTimeColumn varchar(30)='{date_time_column}';
declare #valueColumn varchar(30)='{value_column}';
declare #myTable varchar(20)='{my_table}';
/*Generate Pivot Query */
DECLARE #query AS NVARCHAR(MAX);
set #query= '
SELECT *
FROM (SELECT Cast('+ #dateTimeColumn +' as Date) Resultdate,
       FORMAT(' + #dateTimeColumn + ', ''HH:mm'') DateMinute,
       ' + #valueColumn + ' FROM ' + #myTable + ' ' + #filterQuery +'
     ) FormattedData
PIVOT( AVG('+ #valueColumn + ')  
    FOR DateMinute IN ('+ #timeRange +')
) AS pivotTable
';
/*Execute Generated Query*/
execute(#query)
What you want to do is to return your data in rows, not columns. That is a row for every minute rather than a column for every minute.
Try it something like this:
WITH
cteNums AS
(
Select TOP (1440) ROW_NUMBER() OVER(order by (Select Null)) - 1 as num
From sys.all_columns
Order By num
)
, cteMinutes AS
(
Select FORMAT(CAST(num/cast(1440.0 as real) as DATETIME), N'HH:mm') as Minutes
From cteNums
)
select CAST(t.date_time_column AS DATE) as 'Date',
m.Minutes,
AVG(CASE WHEN FORMAT(t.date_time_column, 'HH:mm') = m.Minute then t.my_values ELSE NULL end) as AvgValues
FROM cteMinutes m
LEFT JOIN [table] t ON m.Minutes = FORMAT(t.date_time_column, 'HH:mm')
where t.date_time_column > '2021-08-12'
GROUP BY CAST(t.date_time_column AS DATE), m.Minutes
ORDER BY CAST(t.date_time_column AS DATE), m.Minutes
;
I cannot, of course, test this as no test data or table definitions were provided.

How to use where clause in Count Function?

i have a query in which i segregate old and new Employee i want to count how many New and old employees are there. how can i segregate and i dont want to use group by cluase.
here is my Query
((SELECT mock.EID,
mock.ECode,
mock.BaseCode,
mock.STATUS,
mock.EmpName,
mock.Desig,
mock.CMP_ID,
CASE WHEN podt.empid IS NULL THEN CAST(0 AS bit)ELSE CAST(1 AS bit)END AS [select],
CONVERT(varchar, mock.JoiningDate, 106) AS JoiningDate,
CASE
WHEN DATEDIFF(DAY, mock.JoiningDate, '1/31/' + CAST(DATEPART(YEAR, GETDATE()) AS varchar)) > 60 THEN 'Old'
ELSE 'New'
END AS StatusEmployee
FROM (SELECT E.EID,
E.ECode,
E.BaseCode,
CASE WHEN E.EActive = 0 THEN 'ACTIVE' ELSE 'IN ACTIVE' END AS STATUS,
E.EmpName,
D.DesigDesc AS Desig,
E.CMP_ID,
CAST(E.JoiningDate AS datetime) AS JoiningDate
FROM PostingDetail pd,
Employee_Profile E,
DESIGNATION D
WHERE pd.EmpId = E.EID
AND E.Desig = D.DesigCode
AND pd.SubLoc IN (6700, 20400, 21300, 21900)
AND pd.EndDate IS NULL
AND CMP_ID IN ('SZSPL')
AND CAST(E.JoiningDate AS datetime) BETWEEN CAST(E.JoiningDate AS datetime) AND '1/31/' + CAST(DATEPART(YEAR, GETDATE()) AS varchar)) mock
LEFT OUTER JOIN PostingDetail_training podt ON mock.EID = podt.empid));
select SUM (CASE WHEN tbl.StatusEmployee= 'New' then 1 else 0 end ) NewEmployee,SUM (CASE WHEN tbl.StatusEmployee= 'Old' then 1 else 0 end ) OldEmployee
from (
(select mock.EID, mock.ECode, mock.BaseCode, mock.STATUS, mock.EmpName, mock.Desig, mock.CMP_ID, case when podt.empid is null then cast(0 as bit) else cast(1 as bit) End [select] ,convert(varchar,mock.JoiningDate,106)JoiningDate,
case when DATEDIFF(day,mock.JoiningDate,'1/31/'+cast(DATEPART(year,getdate())as varchar)) > 60 then 'Old'
else 'New' end as StatusEmployee
from (
SELECT E.EID, E.ECode, E.BaseCode, CASE WHEN E.EActive = 0 THEN 'ACTIVE' ELSE 'IN ACTIVE' END AS STATUS, E.EmpName, D.DesigDesc As Desig, E.CMP_ID ,CAST(E.JoiningDate AS datetime) JoiningDate
FROM PostingDetail pd, Employee_Profile E, DESIGNATION D
Where pd.EmpId = E.EID AND E.Desig = D.DesigCode AND pd.SubLoc in(6700, 20400, 21300, 21900) AND pd.EndDate is null AND CMP_ID IN('SZSPL') and cast(E.JoiningDate as datetime) between cast(E.JoiningDate as datetime) and '1/31/'+cast(DATEPART(year,getdate())as varchar)) mock left outer join PostingDetail_training podt on mock.EID=podt.empid
)) tbl

How to join multi tables with case statement?

How to get data from multiple tables with case on one table, I tried like below but getting error.
select login.UserNname,LastLoggedInDetails.LoggedInIP,UserType.UserType,LastLoggedInDetails.LoggedInTime,
LastLoggedInDetails.LoggedOutTime,LastLoggedInDetails.LoggedInVersion,CompanyRegistered.Comp_Name,
case
when LastLoggedInDetails.LoggedOutTime is not null then CONVERT(VARCHAR(100),DATEDIFF (hour,LastLoggedInDetails.LoggedInTime ,LastLoggedInDetails.LoggedOutTime ))+' Hours '+
CONVERT(VARCHAR(100),DATEDIFF (minute,LastLoggedInDetails.LoggedInTime ,LastLoggedInDetails.LoggedOutTime )%60) +' Minutes' as Duration
when LastLoggedInDetails.LoggedOutTime is null then 'Running...' as Duration
end
from LastLoggedInDetails
join login on LastLoggedInDetails.LastLoggedUserId = login.RegistrationId
join UserType on LastLoggedInDetails.LastLoggedUserTypeId = UserType.UserTypeId
join CompanyRegistered on LastLoggedInDetails.RegCompanyId = CompanyRegistered.Comp_Id
Here is your code for the case, formatted to be helpful:
case when LastLoggedInDetails.LoggedOutTime is not null
then CONVERT(VARCHAR(100),
DATEDIFF(hour, LastLoggedInDetails.LoggedInTime, LastLoggedInDetails.LoggedOutTime)
) + ' Hours ' +
CONVERT(VARCHAR(100),
DATEDIFF(minute, LastLoggedInDetails.LoggedInTime,
LastLoggedInDetails.LoggedOutTime
)%60
) +' Minutes' as Duration
--------------------------------^
when LastLoggedInDetails.LoggedOutTime is null
then 'Running...' as Duration
end
Formatting the code makes the problem obvious: case is an expression that can be named. The individual results from each then are not named. So, try this:
(case when LastLoggedInDetails.LoggedOutTime is not null
then CONVERT(VARCHAR(100),
DATEDIFF(hour, LastLoggedInDetails.LoggedInTime, LastLoggedInDetails.LoggedOutTime)
) + ' Hours ' +
CONVERT(VARCHAR(100),
DATEDIFF(minute, LastLoggedInDetails.LoggedInTime,
LastLoggedInDetails.LoggedOutTime
)%60
) +' Minutes'
when LastLoggedInDetails.LoggedOutTime is null
then 'Running...'
end) as Duration
select login.UserNname,LastLoggedInDetails.LoggedInIP,UserType.UserType,LastLoggedInDetails.LoggedInTime,
LastLoggedInDetails.LoggedOutTime,LastLoggedInDetails.LoggedInVersion,CompanyRegistered.Comp_Name,
case
when LastLoggedInDetails.LoggedOutTime is not null then CONVERT(VARCHAR(100),DATEDIFF (hour,LastLoggedInDetails.LoggedInTime ,LastLoggedInDetails.LoggedOutTime ))+' Hours '+
CONVERT(VARCHAR(100),DATEDIFF (minute,LastLoggedInDetails.LoggedInTime ,LastLoggedInDetails.LoggedOutTime )%60) +' Minutes'
when LastLoggedInDetails.LoggedOutTime is null then 'Running...'
end as Duration
from LastLoggedInDetails
join login on LastLoggedInDetails.LastLoggedUserId = login.RegistrationId
join UserType on LastLoggedInDetails.LastLoggedUserTypeId = UserType.UserTypeId
join CompanyRegistered on LastLoggedInDetails.RegCompanyId = CompanyRegistered.Comp_Id

SQL Case statement based on dates

I need to create a query that includes a CASE statement that basically says
CASE if getdate() > datedue by 31 days
then status = 'Blocked
END
Does anybody know how to check if todays date is greater than say, 25/10/2012 by 31 days?
EDIT
Select co.OrderID, cu.FName + ' ' + cu.SName as 'Name',
cu.Address1 + ', ' + cu.Address2 + ', ' + cu.Address3 as 'Dispatch Address',
cu.PostCode,
ma.MaterialName as 'Item',
mi.Price as 'Item Price',
co.DateOrdered as 'Order Date',
pm.DueDate,
pm.Overdue,
HERE I NEED TO WRITE A CASE STATEMENT TO INSERT INTO A LOCKEDACCOUNT TABLE
so for example CASE WHEN DATEDIFF(dd, GETDATE(), pm.DueDate) >= 31 THEN INSERT INTO LOCKEDACCOUNT (id, status, datelocked, customerid) VALUES (.....)
END
from Customers cu
Like this:
SELECT
CASE
WHEN DATEDIFF(dd, GETDATE(), #duedate) >= 1 THEN 'blocked'
ELSE 'Not'
END AS Status;
SQL Fiddle Demo
Note that: If you didn't specify an ELSE clause, the default will be NULL.
Update: You can insert into a table with CASE expression like so:
INSERT INTO Statuses VALUES
(CASE
WHEN DATEDIFF(dd, GETDATE(), CAST('20121025' AS DATE)) >= 31 THEN 'Blocked'
ELSE 'Not'
END);
Updated SQL Fiddle Demo
select CASE
WHEN DATEDIFF(dd,#duedate,getdate()) >= 31 then 'Blocked' else 'NO' end