Grouping By Date When Used In Case - sql

I've got a working query where I can export to Excel and pivot myself to not be grouped by the fldTrancationDateTime column and that is working fine as a short term solution.
Is the only option here to use SQL pivot so I can only group by the Product and have each date range populated? Instead of one row for each date? Or am I going about coding this incorrectly?
declare #Date Date
set #Date = GETDATE()
print(#Date)
select T.fldProductCode, P.fldProductDescription, count(fldTransactionID),
case when datediff(d,cast(T.fldTransactionDateTime as date),#Date ) <= 7
then count(fldTransactionID) else 0 end as [0-7 Days],
case when datediff(d,cast(T.fldTransactionDateTime as date),#Date ) > 7 and datediff(d,cast(T.fldTransactionDateTime as date),#Date ) <= 14
then count(fldTransactionID) else 0 end as [7-14 Days],
case when datediff(d,cast(T.fldTransactionDateTime as date),#Date ) > 14 and datediff(d,cast(T.fldTransactionDateTime as date),#Date ) <= 21
then count(fldTransactionID) else 0 end as [14-21 Days],
case when datediff(d,cast(T.fldTransactionDateTime as date),#Date ) > 21 and datediff(d,cast(T.fldTransactionDateTime as date),#Date ) <= 28
then count(fldTransactionID) else 0 end as [21-28 Days],
case when datediff(d,cast(T.fldTransactionDateTime as date),#Date ) > 28
then count(fldTransactionID) else 0 end as [28+ Days]
from [transaction] T
join product P on P.fldProductCode = T.fldProductCode
where T.fldTransactionSold = 0
group by P.fldProductDescription,T.fldProductCode, cast(fldTransactionDateTime as DATE)

I am guessing you want conditional aggregation:
select T.fldProductCode, P.fldProductDescription,
count(fldTransactionID),
sum(case when datediff(day, T.fldTransactionDateTime, #Date) <= 7
then 1 else 0
end) as [0-7 Days],
sum(case when datediff(day, T.fldTransactionDateTime, #Date) between 8 and 14
then 1 else 0
end) as [7-14 Days],
sum(case when datediff(day, T.fldTransactionDateTime, #Date) between 15 and 21
then 1 else 0
end) as [14-21 Days],
sum(case when datediff(day, T.fldTransactionDateTime, #Date) between 22 and 28
then 1 else 0
end) as [22-28 Days],
sum(case when datediff(day, T.fldTransactionDateTime, #Date) > 28
then 1 else 0
end) as [21-28 Days],
from [transaction] T join product
P
on P.fldProductCode = T.fldProductCode
where T.fldTransactionSold = 0
group by P.fldProductDescription, T.fldProductCode;;
The case expression is the argument to the sum() rather than the other way around.

Related

Get data of 2 different dates in 2 different columns sql

I have a sql table having columns Name, VisitingDate, StayTime
I want a query which can give me data in which in 1 column I can get data of thismonthvisit and other column I can get data of lastmonthvisit and in 3rd column I can data of summation of StayTime of particular person .
Database Table : --
Name
VisitingDate
StayTime(in minutes)
A
2021-04-20
5
A
2021-04-21
15
A
2021-03-20
10
B
2021-03-20
5
Result Wanted : --
Name
Thismonthvisit
TotalStayTimeThismonth(in minutes)
LastmonthVisit
TotalStayTimelastmonth(in minutes)
A
2
20
1
10
B
0
0
1
5
Here is what you are looking for :
select name,
SUM(CASE WHEN FORMAT(VisitingDate, 'YYYYMM') = FORMAT(getdate(),'YYYYMM') THEN 1 ELSE 0 END) AS ThisMonthVisit,
SUM(CASE WHEN FORMAT(VisitingDate, 'YYYYMM') = FORMAT(getdate(),'YYYYMM') THEN StayTime ELSE 0 END) AS TotalStayTimeThisMonth,
SUM(CASE WHEN FORMAT(VisitingDate, 'YYYYMM') = FORMAT(dateadd(month, -1, getdate()),'YYYYMM') THEN 1 ELSE 0 END) AS LastMonthVisit,
SUM(CASE WHEN FORMAT(VisitingDate, 'YYYYMM') = FORMAT(dateadd(month, -1, getdate()),'YYYYMM') THEN StayTime ELSE 0 END) AS TotalStayTimeLastMonth
from MyTable
where FORMAT(VisitingDate, 'YYYYMM') > FORMAT(dateadd(month, -2, getdate()),'YYYYMM')
group by Name
SEE DEMO HERE
You can use aggregation:
select name,
sum(case when month(visitingdate) = month(getdate())
then 1 else 0
end) as cnt_thismonth,
sum(case when month(visitingdate) = month(getdate())
then staytime else 0
end) staytime_thismonth,
sum(case when month(visitingdate) <> month(getdate())
then 1 else 0
end) as cnt_lastmonth,
sum(case when month(visitingdate) <> month(getdate())
then staytime else 0
end) staytime_lastmonth
from t
where visitingdate >= dateadd(month, -1, datefromparts(year(getdate()), month(getdate()), 1))
group by name;

T-SQL pivot inventory aging by day range

Writing a T-SQL statement to display items in inventory broken out by day range (pivot).
For example from this inventory table:
ItemName
DateCreated
PO_ID
A
2020-10-07
0
B
2020-10-07
1
A
2020-10-22
2
A
2020-10-22
2
A
2020-10-22
2
B
2020-10-29
3
Would like to generate the bellow results (typically a pivot table), showing the number of pieces per ItemName per day range. The date used to calculate the # of days since DateCreated would be the day the report was ran or passed in as a parameter - in the example shown here, the date used is from '2020-11-07':
ItemName
0-10 days
11-20 days
21-30 days
>30 days
A
0
3
0
1
B
1
0
0
1
Not sure what would be the best way to write the statement to generate the above results?
I would use conditional aggregation:
select itemName,
sum(case when datediff(day, dateCreated, getdate()) <= 10 then 1 else 0 end) as days_0_10,
sum(case when datediff(day, dateCreated, getdate()) > 10 and
datediff(day, dateCreated, getdate()) <= 20
then 1 else 0 end) as days_11_20,
sum(case when datediff(day, dateCreated, getdate()) > 20 and
datediff(day, dateCreated, getdate()) <= 30
then 1 else 0 end) as days_21_30,
sum(case when datediff(day, dateCreated, getdate()) > 30 then 1 else 0 end) as days_31
from t
group by itemName
I would use something similar to the following query SQL Server:
SELECT *
FROM
(
SELECT [ItemName],[PO_ID],
CASE
WHEN DATEDIFF(day, DateCreated, getdate()) BETWEEN 0 AND 10 THEN '0-10 days'
WHEN DATEDIFF(day, DateCreated, getdate()) BETWEEN 11 AND 20 THEN '11-20 days'
WHEN DATEDIFF(day, DateCreated, getdate()) BETWEEN 21 AND 30 THEN '21-30 days'
ELSE '>30 days'
END AS PeriodCreated
FROM [TableName])
) src
pivot
(
COUNT(PO_ID)
FOR PeriodCreated in ([0-10 days], [11-20 days], [>30 days])
) piv

Get the last 14 days of records not included current date

I'm having trouble with the dates. I have here my code to count the records for the last 14 days from the current date but not including TODAY in the display.
Here's my SQL query
SELECT
a.TrackingCode,
a.SegmentName,
a.Brand,
a.DateAdded,
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 1 THEN 1 ELSE NULL END) as "Day_1",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 2 THEN 1 ELSE NULL END) as "Day_2",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 3 THEN 1 ELSE NULL END) as "Day_3",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 4 THEN 1 ELSE NULL END) as "Day_4",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 5 THEN 1 ELSE NULL END) as "Day_5",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 6 THEN 1 ELSE NULL END) as "Day_6",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 7 THEN 1 ELSE NULL END) as "Day_7",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 8 THEN 1 ELSE NULL END) as "Day_8",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 9 THEN 1 ELSE NULL END) as "Day_9",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 10 THEN 1 ELSE NULL END) as "Day_10",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 11 THEN 1 ELSE NULL END) as "Day_11",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 12 THEN 1 ELSE NULL END) as "Day_12",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 13 THEN 1 ELSE NULL END) as "Day_13",
COUNT(CASE WHEN DATEDIFF(DD, a.DateAdded, GETDATE()) = 14 THEN 1 ELSE NULL END) as "Day_14"
FROM
Journey_Injection_Logger_Base a
WHERE
a.DateAdded >= DATEADD(DD, -14, GETDATE())
AND a.DateAdded <= GETDATE()
GROUP BY
a.TrackingCode, a.SegmentName, a.Brand, a.DateAdded
The Day_1 is the yesterday's date. The problem is that when the next day comes it will add the new current date and my records for the Day_1 is not moving.
Sample output
enter image description here
From the above image of sample output. The record 2 should be in 4/14 TUE

Group by year in sql

I am trying to group by year but was not able to do.I can get the column count but not year wise. this is what i tried.
select t_contract ,
sum(CASE t_contract when '18' then 1 else 0 end) as XL,
sum(CASE t_contract when '01' then 1 else 0 end) as VC,
sum(CASE t_contract when '75' then 1 else 0 end) as AN,
sum(CASE t_contract when '48' then 1 else 0 end) as CS
from icps.dbo.tickets
WHERE
t_date_time_issued >= DATEADD(year, -6, GETDATE())
GROUP BY contract
.. but i want to add year .. where i have t_date_time _issued column.
My another query is I have a column called t_zone_name and I want to sum all the rows where t_zone_anme like '%ICeland%' an i tried this:
sum(CASE t_zone_name like '%ICeland%' then 1 else 0 end) as ICELAND
but I get an error on statement like... thanks in advance.
LIKE
YEAR XL VC AN CS total
2010 50 50 50 50 200
2011 5 5 5 5 20
Try the below query:
SELECT t_contract, YEAR(t_date_time_issued) As Yr, SUM(CASE WHEN t_zone_name like '%ICeland%' THEN 1 ELSE 0 END) AS ICELAND
SUM(CASE t_contract when '18' then 1 else 0 end) as XL,
SUM(CASE t_contract when '01' then 1 else 0 end) as VC,
SUM(CASE t_contract when '75' then 1 else 0 end) as AN,
SUM(CASE t_contract when '48' then 1 else 0 end) as CS
FROM icps.dbo.tickets
WHERE YEAR(t_date_time_issued) >= (YEAR(GetDate()) - 6)
GROUP BY t_contract, YEAR(t_date_time_issued)
You might need change the order of t_contract and YEAR(t_date_time_issued) depending on which grouping you want to apply first.
As suggested by #ray I have replaced DATEPART(yyyy, t_date_time_issued) >= DATEPART(yyyy, DATEADD(year, -6, GETDATE())) with year(t_date_time_issued) >= (year(GetDate()) - 6)
If you want to group by year, in sql server, you might
GROUP BY DATEDIFF(year,t_date_time_issued, GETDATE())
In other DB engine, usually has method to get year part, or use substring to get year part from a time string.

1 part of case clause not working correctly

im having a little trouble with a case clause. The problem is in the last portion ending in DueBeyond, i need this to return any of our orders in our system that is due beyond tomorrow, as in 2 days from today. sorry to be overly obvious.
SUM(CASE WHEN CURRENT_TIMESTAMP > oi.RequiredByDate THEN 1 ELSE 0 END) as PastDue
,SUM(CASE WHEN DATEADD(dd, DATEDIFF(dd, 0, oi.RequiredByDate), 0) = dateadd(day, datediff(day, '19000101',CURRENT_TIMESTAMP),'19000102') then 1 ELSE 0 END) as DueTomorrow
,SUM(CASE WHEN dbo.TruncateDate(CURRENT_TIMESTAMP) = dbo.TruncateDate(oi.RequiredByDate) THEN 1 Else 0 END) as DueToday
,SUM(CASE WHEN DateDiff(day, getdate(), RequiredByDate) BETWEEN 2 and 7 AND DateName(weekday, RequiredByDate) = 'Monday' Then 1 ELSE 0 END) as DueMonday
,SUM(CASE WHEN dbo.TruncateDate(CURRENT_TIMESTAMP) <= dbo.TruncateDate(oi.RequiredByDate) THEN 1 ELSE 0 END) as DueBeyond
If you add two days to the current date and then see if that is still less than or equal to your required date it must be no sooner than two days in the future.
,SUM(CASE WHEN DATEADD(DAY, 2,dbo.TruncateDate(CURRENT_TIMESTAMP)) <=
dbo.TruncateDate(oi.RequiredByDate) THEN 1 ELSE 0 END) as DueBeyond