Date Restriction-SQL Query - sql

I have this query in my ssis package and I would like to add a constraint where if the data is more than 4 days old to not add it, how would I add that into this?
SELECT PTA,
Part,
Duns,
YearStart AS BlanketYear,
VIPDoc,
DID,
STATUS = CASE
WHEN STATUS IS NULL
THEN 'Eligible'
ELSE STATUS
END,
[PRTCOMACERT STATUS] AS TMSStatus,
SupplierHTS1 AS HTS,
PrefCrit,
Producer,
NetCost,
CoCountry AS Country,
TracedValue,
Currency,
MaCountry,
VEH,
ENG,
KitPercent,
DateCreated,
DATEDIFF(d, DateCreated, GetDate()) AS AGE
FROM [SourceTempFCA].[dbo].[FCAStatus] g
INNER JOIN [SourceTempFCA].[dbo].[NEW35COMA] t ON g.part = t.PART#PART#
AND g.duns = t.[PRTCOMASUPPLIER #]
AND g.yearstart = t.[PRTCOMAEXP DATE Year]
AND g.VIPDoc = t.[PRTCOMADOC #]
--delete from [SourceTempFCA].[dbo].[FCAStatus]

This is just a SELECT statement so I'm assuming you mean to filter out those rows? Then just do
WHERE DATEDIFF(d, DateCreated, GetDate()) > 4

Related

How do I show the percentage of a group in SQL?

I am trying to show the percentage of tasks completed before a certain deadline, for separate groups.
I have calculated the percentage for the whole, but when I try to split the data into a calculation for each group I keep getting errors.
To calculate the percentage, I have been using:
DECLARE #TM DATETIME;
SET #TM = DATEADD(MONTH,DATEDIFF(MONTH,'19000101', GETDATE()), '19000101')
SELECT CAST(
(
SELECT COUNT (a.[completed])
FROM [table] a
JOIN [other table] b
ON a.TaskID = b.TaskID
WHERE a.[completed] >= DATEADD(MONTH,0,#TM) AND
b.[completedByDeadline] = 1) AS DECIMAL (10,2))
/
CAST(
(
SELECT COUNT([completed])
FROM [table]
WHERE [completed] >= DATEADD(MONTH,0,#TM))
*100 AS Decimal (10,2))
When I try to add the [groupName] column to the SELECT list and a GROUP BY clause, there are errors; it mentions the need for an EXISTS keyword, but I can't see where to put one.
Any help that people could provide would be fantastic! Thanks.
I would just use this:
DECLARE #TM DATETIME;
SET #TM = DATEADD(MONTH,DATEDIFF(MONTH,'19000101', GETDATE()), '19000101')
SELECT
COUNT (case
when b.[completedByDeadline] = 1
then 1
else NULL
end) / COUNT (a.[completed])
FROM [table] a
LEFT JOIN [other table] b
ON a.TaskID = b.TaskID
WHERE a.[completed] >= DATEADD(MONTH,0,#TM)
I like using AVG() for this sort of query:
SELECT AVG(case when b.[completedByDeadline] = 1 then 1.0 else 0
end)
FROM [table] a LEFT JOIN
[other table] b
ON a.TaskID = b.TaskID
WHERE a.[completed] >= DATEADD(MONTH, 0, #TM);
If completedByDeadline only takes on the values 0 and 1, this can be simplified further:
SELECT AVG(b.[completedByDeadline] * 1.0)
FROM [table] a LEFT JOIN
[other table] b
ON a.TaskID = b.TaskID
WHERE a.[completed] >= DATEADD(MONTH, 0, #TM);
Note that these will return NULL if there are no corresponding tasks in b.

Count of record, per day, by user comparative

Looking to see if there is a way to compare the number of orders entered a day and by either a specific user (EDI) or anyone else.
I can return results for per day (but only the days where a value exists) but can't figure out a way to combine all three together (Total - by EDI - by everyone else).
Any assistance greatly appreciated.
select Date, count(Order_ID)
from orders
WHERE Date >=dateadd(day,datediff(day,0,GetDate())- 7,0) and [user] = 'EDI'
and customer = '9686'
GROUP BY Date, [user];
select Date, count(Order_ID)
from orders
WHERE Date >=dateadd(day,datediff(day,0,GetDate())- 7,0) and [user] <> 'EDI'
and customer = '9686'
GROUP BY Date, [user];
select Date, count(Order_ID)
from orders
WHERE Date >=dateadd(day,datediff(day,0,GetDate())- 7,0)
and customer = '9686'
GROUP BY Date, [user];
Use conditional aggregation:
select Date, sum(case when [user] = 'EDI' then 1 else 0 end) as cnt_edi,
sum(case when [user] <> 'EDI' then 1 else 0 end) as cnt_non_edi,
count(*) as total
from orders
where Date >= dateadd(day, datediff(day, 0, GetDate()) - 7, 0) and customer = '9686'
group by Date;

Is it possible to add second where condition to select this same data but from other date range?

I have two tables in SQL Server.
I want to select DeptCode, DeptName, YearToDate, PeriodToDate (2 months for example) and group it by DeptCode.
There is a result which I want to get:
In YTD column I want to get sum of totalCost since 01/01/actualYear.
In PTD column I want to get the sum from last two months.
I created a piece of code which shows me correct YTD cost but I don't know how I can add next one for getting total cost for other date range. Is it possible to do this?
SELECT
d.DeptCode,
d.DeptName,
SUM(s.TotalCost) as YTD
FROM [Departments] AS d
INNER JOIN Shipments AS s
ON d.DeptCode= s.DeptCode
WHERE s.ShipmentDate BETWEEN DateAdd(yyyy, DateDiff(yyyy, 0, GetDate()), 0)
AND GETDATE()
GROUP BY d.DeptCode, d.DeptName
Your expected output doesn't match 2 months, but here's the code to accomplish what you want. You just have to add a SUM(CASE...) on the 2nd condition.
SELECT
d.DeptCode,
d.DeptName,
SUM(s.TotalCost) as YTD,
SUM(CASE WHEN s.ShipmentDate >= DATEADD(month, -2, GETDATE()) then s.TotalCost else 0 END) as PTD
FROM [Departments] AS d
INNER JOIN Shipments AS s
ON d.DeptCode= s.DeptCode
WHERE Year(s.ShipmentDate) = Year(GETDATE())
GROUP BY d.DeptCode, d.DeptName
Just add one more column that returns 0 when not in the two-month range, e.g. SUM(CASE WHEN (date check) THEN (amount) ELSE 0 END). Check out the fifth line:
SELECT
d.DeptCode,
d.DeptName,
SUM(s.TotalCost) as YTD,
SUM(CASE WHEN DateDiff(MONTH, s.ShipmentDate, GetDate()) < 2 THEN s.TotalCost ELSE 0 END) PTD,
FROM [Departments] AS d
INNER JOIN Shipments AS s
ON d.DeptCode= s.DeptCode
WHERE s.ShipmentDate BETWEEN DateAdd(yyyy, DateDiff(yyyy, 0, GetDate()), 0)
AND GETDATE()
GROUP BY d.DeptCode, d.DeptName
Try this one :
nbr_last2month_ AS
(
SELECT DISTINCT
Sum(s.[TotalCost]) AS 'PTD',
s.DeptCode,
s.DeptName
FROM [Shipements] s
LEFT JOIN [Departements] d ON d.[DeptCode] = s.[DeptCode]
WHERE Year(date_) LIKE Year(GETDATE())
AND MONTH(ShipementDate) LIKE Month(Getdate()) - 2
Group by DeptCode
),
nbr_YTD_ AS
(
SELECT DISTINCT
Sum(s.[TotalCost]) AS 'YTD',
s.DeptCode,
s.DeptName
FROM [Shipements] s
LEFT JOIN [Departements] d ON d.[DeptCode] = s.[DeptCode]
WHERE Year(ShipementDate) LIKE Year(GETDATE())
Group by DeptCode
),
SELECT
A.DeptCode,
A.DeptName,
YTD,
PTD
FROM nbr_YTD_ A
LEFT JOIN nbr_last2month_ B on B.DeptCode = A.DeptCode
ORDER BY DeptCode

Retrieve last record from current month and previous month

I need to get the last recorded value from the current month and the previous month. There are roughly 4,600 records per month.
The following is the code I have tried, however it returns '0' for the two months and not the value:
SELECT a.LogPoint as [Meter]
,max(CASE WHEN c.DateTimeStamp = dateadd(MM,-1,getdate()) THEN c.FloatVALUE ELSE 0 END) as [Total LAST Month]
,max(CASE WHEN c.DateTimeStamp = getdate() THEN c.FloatVALUE ELSE 0 END) as [Total This Month]
FROM
SWR.dbo.LoggedEntities a
,SWR.dbo.TrendLogRelation b
,SWR.dbo.LogTimeValues c
WHERE
a.GUID = b .GUID
AND a.Type LIKE 'trend.ETLog'
AND a.LogPoint = 'WsumOut_Trnd'
AND b.EntityID = c.ParentID
GROUP BY a.LogPoint
Any help would be greatly appreciated.
Cheers.
I assume the LogPoint is the primary key. correct? In that case check following:
SELECT mainA.LogPoint AS [Meter],
lastMonth.FloatValue AS [Total LAST Month],
thisMonth.FloatValue AS [Total This Month]
FROM SWR.dbo.LoggedEntities mainA
CROSS APPLY
(
SELECT TOP 1 c.FloatVALUE
FROM SWR.dbo.LoggedEntities a
JOIN SWR.dbo.TrendLogRelation b ON a.GUID = b.GUID
JOIN SWR.dbo.LogTimeValues c ON b.EntityID = c.ParentID
WHERE a.LogPoint = mainA.LogPoint
ORDER BY c.DateTimeStamp DESC
) thisMonth
CROSS APPLY
(
SELECT TOP 1 c.FloatVALUE
FROM SWR.dbo.LoggedEntities a
JOIN SWR.dbo.TrendLogRelation b ON a.GUID = b.GUID
JOIN SWR.dbo.LogTimeValues c ON b.EntityID = c.ParentID
WHERE a.LogPoint = mainA.LogPoint AND c.DateTimeStamp <= DATEADD(MM,-1,GETDATE())
ORDER BY c.DateTimeStamp DESC
) lastMonth
WHERE a.Type LIKE 'trend.ETLog'
AND a.LogPoint = 'WsumOut_Trnd';
Just realized that I missed the last month date check. added now. try that :)
getdate() includes both the time and the date, which is why you aren't getting any matches.
One option is to cast both values to dates and then do the comparison.
Two important points before I start:
Never use commas in the FROM clause. Always use explicit JOIN syntax.
Table aliases should be abbreviations for the table.
Then, you want to use row_number():
SELECT LogPoint as [Meter],
max(CASE WHEN seqnum = 1 AND
DATEDIFF(month, DateTimeStamp, getdate()) = 1
THEN cltv.FloatVALUE
END) as [Total LAST Month],
max(CASE WHEN seqnum = 1 AND
DATEDIFF(month, DateTimeStamp, getdate()) = 0
THEN ltv.FloatVALUE
END) as [Total This Month]
FROM (SELECT le.LogPoint, ltv.DateTimeStamp,
ROW_NUMBER() OVER (PARTITION BY YEAR(DateTimeStamp), MONTH(DateTimeStamp)
ORDER BY DateTimeStamp DESC
) as seqnum
FROM SWR.dbo.LoggedEntities le JOIN
SWR.dbo.TrendLogRelation tlr
ON le.GUID = tlr.GUID JOIN
SWR.dbo.LogTimeValues ltv
ON ltr.EntityID = ltv.ParentID
WHERE le.Type LIKE 'trend.ETLog' AND
le.LogPoint = 'WsumOut_Trnd' AND
DATEDIFF(month, ltv.DateTimeStamp, getdate()) IN (0, 1)
) x
WHERE seqnum = 1;

IF statement on query results

I have the results of the query below emailed everyday 90% of the time empty. I would like to add an if statement to only send the email If (resulting row count>0)
Select Orders.TransactionNumber, Orders.RepNumber, Orders.CustomerID,
Orders.ShipToId, orders.ItemCode, Orders.Quantity, Orders.ReceivedDate,
Orders.TransmitStatus from (select TransactionNumber from Orders
group by TransactionNumber
having count (TransactionNumber = 1) as transa
inner join Orders on Orders.TransactionNumber = transa.TransactionNumber
where ItemCode = 9987 and ReceivedDate > DateAdd(day, -4, GetDate())
order by ReceivedDate
Add here if (counted rows>0 send the email else end)
Any DML(SELECT,INSERT,UPDATE) operations in SQLServer captured in global variable called ##ROWCOUNT. Use that in your case as well.
Select Orders.TransactionNumber, Orders.RepNumber, Orders.CustomerID,
Orders.ShipToId, orders.ItemCode, Orders.Quantity, Orders.ReceivedDate,
Orders.TransmitStatus from (select TransactionNumber from Orders
group by TransactionNumber
having COUNT (TransactionNumber)=1) as transa
Inner join Orders on Orders.TransactionNumber=transa.TransactionNumber
where ItemCode=9987 and ReceivedDate > DateADD (day, -4, GetDate() )
Order by ReceivedDate
IF ##ROWCOUNT > 0
PRINT 'send mail<your logic goes here>'
Couldn't you apply:
Orders.TransactionNumber != ""
to your where statement to get query results that aren't empty?