query to generate transactions from previous month - sql

I need to write a query which when executed at the beginning of the current month must generate a report which contains total transactions made in the previous month and I have written the below query:
SELECT
l.state AS Province
,l.taxing_entity AS TaxJurisdiction
,COUNT(DISTINCT t.trans_id) AS TotalTransCount
FROM TRANSACTION AS t
LEFT OUTER JOIN location AS l
ON t.location_id = l.location_id
LEFT OUTER JOIN trans_line AS tl
ON t.trans_id = tl.trans_id
LEFT OUTER JOIN contract as c
ON t.contract_id = c.contract_id
WHERE
l.chain_id = 10
AND c.issuer_id IN (156967)
AND t.extra_5 BETWEEN LAST_DAY(TODAY - 2 units month) + 1 units day AND LAST_DAY(TODAY - 1 units month)
AND tl.cat NOT IN ('DEF','DEFD','DEFC')
GROUP BY l.state, l.taxing_entity, Province
ORDER BY l.state,l.taxing_entity
But this query throws an error "It is not possible to convert between the specified types. ". I tried changing the date range as below:
t.extra_5 >= DATEADD(MONTH, DATEDIFF(MONTH, 31, CURRENT_TIMESTAMP), 0) AND t.extra_5 < DATEADD(MONTH, DATEDIFF(MONTH, 0, CURRENT_TIMESTAMP), 0)
and
t.extra_5 > DateAdd(WEEK, -1, GETDATE()+1) and t.extra_5<=GETDATE()
But nothing has worked out so far. The current format for the column "extra_5" is as below:
Can someone please suggest a way to get the total transactions from previous month.

Related

a query displaying 0 instead of not showing

the following query is displaying the result i want except i want it to show 0 for each month with non production.
SELECT
DATENAME(MONTH, DATEADD(M, MONTH(PolicyDetails.IssuedDate), - 1)) AS Month,
SUM(PolicyDetails.Premium) AS TotalProduction,
DATENAME(YEAR, PolicyDetails.IssuedDate) AS Year
FROM PolicyDetails INNER JOIN Clients
ON PolicyDetails.ClientId = Clients.ClientId
WHERE (Clients.Username = #Username)
GROUP BY MONTH(PolicyDetails.IssuedDate), DATENAME(YEAR, PolicyDetails.IssuedDate)
Month Total Production -$$
2019 - August 30.00
2019 - October 45.00
in this table i want to show "2019 - September" with Total Production = 0 instead of displaying nothing. How ??
If you want to show all months in the data, probably the simplest method is to use conditional aggregation. Your calculation of the month seems awkward. You seem to want the previous month, so:
SELECT DATENAME(YEAR, pd.IssuedDate) AS Year,
DATENAME(MONTH, DATEADD(MONTH, -1, pd.IssuedDate)) AS Month,
SUM(CASE WHEN c.Username = #Username THEN pd.Premium ELSE 0 END) AS TotalProduction
FROM PolicyDetails pd INNER JOIN
Clients c
ON pd.ClientId = c.ClientId
GROUP BY DATENAME(YEAR, pd.IssuedDate), DATENAME(MONTH, DATEADD(MONTH, -1, pd.IssuedDate))
ORDER BY MIN(pd.IssuedDate)
This assumes that you have at least one row per month in the data.
Otherwise, the canonical approach is to generate the months you want (using a derived table or recursive CTE or calendar table). Your month arithmetic is a bit awkward for that solution. It would look like:
SELECT YEAR(DATEADD(MONTH, -1, months.mstart)),
MONTH(DATEADD(MONTH, -1, months.mstart)),
COALESCE(SUM(pd.Premium), 0) AS TotalProduction
FROM (VALUES (CONVERT(DATE, '2019-08-01')),
(CONVERT(DATE, '2019-09-01')),
(CONVERT(DATE, '2019-10-01'))
) months(mstart) LEFT JOIN
PolicyDetails pd
ON pd.IssuedDate >= DATEADD(month, -1, months.mstart) AND
pd.IssuedDate < months.mstart LEFT JOIN
Clients c
ON pd.ClientId = c.ClientId AND
c.Username = #Username
GROUP BY YEAR(DATEADD(MONTH, -1, months.mstart)),
MONTH(DATEADD(MONTH, -1, months.mstart))
ORDER BY MIN(pd.IssuedDate)
I suppose that might be a usecase for SQL-IF.
Syntax as follows:
SELECT IF([condition], "YES", "NO");
In your case, try to combine that with your query.
Maybe like this:
SELECT IF([subquery > 0] AS X, X, 0);
If-Condition Like:
SELECT IF((SELECT COUNT(*) FROM PolicyDetails ) > 0, 1, 0);
But you will have to combine that output with your existing query posted above, to gain the output if the table is filled.

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

Trying to find 12 week average by weekday basis

I am trying to find 12 weeks average through same weekday.
Example:
weekday sale
So basically I need the average based on the number of stores having net > 0. for yellow color, it should be total/11 as there is no sale for 02-07-16
I have written this query but it doesn't work properly. Could you guys please help me?
SELECT Store_DateJoined.StoreKey, Store_DateJoined.RestaurantName, Store_DateJoined.Ownership, Store_DateJoined.DateKey,
Sales_Summary.Net, Sales_Summary.[LastWeek_Net],
(SELECT AVG(Net) AS AVGNET
FROM (SELECT TOP (12) Net
FROM DailySummary AS FB INNER JOIN
DimDate ON FB.DateKey = DimDate.DateKey
WHERE datename(WEEKDAY, TransactionDate) IN (select datename(WEEKDAY, TransactionDate) from [NandosDW].[dbo].[DailySummary]) and (FB.StoreKey = Store_DateJoined.StoreKey) AND (FB.DateKey <= Store_DateJoined.DateKey) AND
(DimDate.DayNameOfWeek = Store_DateJoined.DayNameOfWeek) AND (FB.DateKey >= (FB.DateKey - 84))
ORDER BY FB.DateKey, StoreKey DESC) AS WAVGNET) AS [Week12_Net],
Store_DateJoined.FullDate, Store_DateJoined.DayNameOfWeek, Store_DateJoined.FinancialWC, Store_DateJoined.strFinancialWeek
FROM Sales_Summary RIGHT OUTER JOIN Store_DateJoined LEFT OUTER JOIN
DimLFL ON Store_DateJoined.StoreKey = DimLFL.StoreKey AND Store_DateJoined.DateKey = DimLFL.DateKey ON
Sales_Summary.RedCatID = Sore_DateJoined.StoreKey AND
Sales_Summary.DateKey = Store_DateJoined.DateKey
I havent included the joins in this query, but they are present

Combining the results of two JOINS in SQL

Tickets last 24 hours and can be either 'Child', 'Adult' or 'Teen'. Essentially, a ticket can be 'ConnectedTo' a number of movies. Child tickets for example will be connected to movies with a age rating of PG or below, while Adult tickets will be connected to every single movie.
The below returns info on all the tickets purchased for movies from the previous month:
SELECT *
FROM
[Test_DB].[dbo].[Tickets]
INNER JOIN
[Test_DB].[dbo].[Movies]
ON
[Test_DB].[dbo].[Tickets].[ConnectedTo] = [Test_DB].[dbo].[Movies].[MovieID]
WHERE
[Test_DB].[dbo].[Tickets].[DateEntered] >= DATEADD(month, DATEDIFF(month, 0, GETDATE())-1, 0) AND [Test_DB].[dbo].[Tickets].[DateEntered] <= DATEADD(month, DATEDIFF(month, 0, GETDATE()), -1)
Each ticket can have any number of notes attached to it. For example, if a special discount was given to a ticket holder, a note will be created about that. Similiarly, if a ticket is exchanged for another or refunded, a note will be created.
The below will return all the notes for a given Ticket based on the TicketID:
SELECT *
FROM
[Test_DB].[dbo].[Tickets]
JOIN [Test_DB].[dbo].[Notes]
ON [Test_DB].[dbo].[Tickets].[TicketID] = [Test_DB].[dbo].[Notes].[ConnectedTo]
WHERE TicketId = 64903
My question is, is there a way to combine the two? For example, the first bit of SQL could return 5 tickets, each with a different TicketID. Based on that, I want to make use of my second SQL to return all of the notes for those 5 tickets.
I was thinking of using UNION to combine the two selects... Though my brain keeps telling me that I need to JOIN the two pieces of SQL on the TicketId's, however every time I try to it comes out wrong. Any help would greatly be appreciated! Thanks.
This should work
SELECT [Test_DB].[dbo].[Tickets].*, [Test_DB].[dbo].[Notes].*
FROM [Test_DB].[dbo].[Tickets]
INNER JOIN [Test_DB].[dbo].[Movies]
ON
[Test_DB].[dbo].[Tickets].[ConnectedTo] = [Test_DB].[dbo].[Movies].[MovieID]
INNER JOIN [Test_DB].[dbo].[Notes]
ON [Test_DB].[dbo].[Tickets].[TicketID] = [Test_DB].[dbo].[Notes].[ConnectedTo]
WHERE [Test_DB].[dbo].[Tickets].[DateEntered] >= DATEADD(month, DATEDIFF(month, 0, GETDATE())-1, 0)
AND [Test_DB].[dbo].[Tickets].[DateEntered] <= DATEADD(month, DATEDIFF(month, 0, GETDATE()), -1)
I imagine that "notes" could be optional. If so, then you will want a left join rather than an inner join. Also, the use of aliases and eliminating the unnecessary square brackets would make your query easier to read:
SELECT *
FROM Test_DB.dbo.Tickets t INNER JOIN
Test_DB.dbo.Movies m
ON t.ConnectedTo = m.MovieID LEFT JOIN
Test_DB.dbo.Notes n
ON t.TicketID = n.ConnectedTo
WHERE t.DateEntered >= DATEADD(month, DATEDIFF(month, 0, GETDATE()) -1, 0) AND
t.DateEntered <= DATEADD(month, DATEDIFF(month, 0, GETDATE()), -1);
Note (no pun intended): if a ticket has multiple notes, then you will get multiple rows in the output.

Facing issue in Access Database query

Order Table Schema
My Access Database Query
Select * from
(
SELECT reseller.id, Max(orders.[order date]) as OrderDate
FROM Reseller INNER JOIN orders ON Reseller.ID = orders.ResellerID
group by reseller.id
)K
WHERE (((K.[OrderDate]) Not Between (Date()-1) And (Date()-18)))
To find those reseller that did not order for 18 Days.
But this is giving below records
Am I missing something ?
Try this query instead:
SELECT *
FROM
(
SELECT reseller.id, Max(orders.[order date]) AS OrderDate
FROM
Reseller
INNER JOIN
orders
ON Reseller.ID = orders.ResellerID
GROUP BY reseller.id
) K
WHERE DateDiff("d", K.[OrderDate], Date()) > 18
Try this
Select * from
(
SELECT reseller.id, Max(orders.[order date]) as OrderDate
FROM Reseller INNER JOIN orders ON Reseller.ID = orders.ResellerID
group by reseller.id
)
WHERE (((K.[OrderDate]) Not Between ( DateAdd("d", -1, Date())
And DateAdd("d", -18, Date())
)
I think when you do Date() - 1 it is subtracting 1 time internal until like subpart of second from the date, not what you intended to subtract 1 date
ALSO, did not change, but do you really want to make the top limits today - 1 day, or just today?