SQL accumulate of query with sum - sql

I have this query in SQL:
select cast(faturas.datatotal as date) as Dia, faturas.sumF, credito.sumC, isnull(sumF,0)-isnull(sumC,0) as Total
from
(SELECT SUM([Line Amount]) as sumF, [Posting Date] as datatotal
FROM [CMW$Sales Invoice Line]
where [CMW$Sales Invoice Line].[Posting Date] >= '2017-01-01'
group by [CMW$Sales Invoice Line].[Posting Date]) faturas
full outer join
(SELECT SUM(Amount) as sumC, [Posting Date]
FROM [CMW$Sales Cr_Memo Line]
where [CMW$Sales Cr_Memo Line].[Posting Date] >= '2017-01-01'
group by [CMW$Sales Cr_Memo Line].[Posting Date]) credito
on faturas.datatotal=credito.[Posting Date]
I need to calculate the cumulative "Total" in this same query. How can I get this?

I solved my problem with this:
sum(isnull(sumF,0)-isnull(sumC,0)) over(order by faturas.datatotal rows unbounded preceding) as Acumulado
Thanks

Related

SQL query to find last date before and all dates after a condition using CASE statement

• Suppliers having PO date before 01 Jan 21 won’t be considered
• Exception-If all suppliers have PO date before 1 Jan 21, supplier with latest PO date will be considered.
Check the image for reference
SELECT
A.IPN,
A.[Manufacturer/Supplier],
A.[Last PO#],
A.[Last PO Date]
FROM (
SELECT
*,
ROW_NUMBER() OVER (PARTITION BY IPN,[Manufacturer/Supplier]
ORDER BY
(CASE
WHEN [Last PO Date] >= '01/01/2021'
THEN [Last PO Date]
WHEN [Last PO Date] < '01/01/2021'
THEN MAX([Last PO Date])
ELSE NULL
END)
DESC, IPN DESC) AS rn
FROM dbo.Sheet1$
) A
WHERE rn = 1
Can anyone explain?
I used a common table expression (CTE) for selecting records when there are no rows after 2021-01-01, ordering by date.
WITH DATA_CTE AS (
SELECT
A.IPN,
A.[Manufacturer/Supplier],
A.[PO#],
A.[PO Date]
FROM
dbo.Sheet1$ A
WHERE
A.[PO Date] < '2021-01-01'
AND NOT EXISTS(
SELECT B.IPN
FROM dbo.Sheet1$ B
WHERE B.[PO Date] >= '2021-01-01'
)
ORDER BY A.[PO Date] DESC
)
SELECT
A.IPN,
A.[Manufacturer/Supplier],
A.[PO#],
A.[PO Date]
FROM
dbo.Sheet1$
WHERE
A.[Last PO Date] >= '2021-01-01'
UNION
SELECT
TOP 1
A.IPN,
A.[Manufacturer/Supplier],
A.[PO#],
A.[PO Date]
FROM
DATA_CTE

How to select max date over the year function

I am trying to select the max date over the year, but it is not working. Any ideas on what to do?
SELECT a.tkinit [TK ID],
YEAR(a.tkeffdate) [Rate Year],
max(a.tkeffdate) [Max Date],
tkrt03 [Standard Rate]
FROM stageElite.dbo.timerate a
join stageElite.dbo.timekeep b ON b.tkinit = a.tkinit
WHERE a.tkinit = '02672'
and tkeffdate BETWEEN '2014-01-01' and '12-31-2014'
GROUP BY a.tkinit,
tkrt03,
a.tkeffdate
Perhaps you only want it by year and not rolled up by calendar date. For SQL server you can try this.
SELECT
…
MaxDate = MAX(a.tkeffdate) OVER (PARTITION BY a.tkinit, YEAR(a.tkeffdate)))
…
Or you could modify the query above to group by the year instead of date-->
GROUP BY a.tkinit,
tkrt03,
YEAR(a.tkeffdate)
You seem to want only one row and all the columns. Use ORDER BY and TOP:
SELECT TOP (1) tr.tkinit as [TK ID],
YEAR(tr.tkeffdate) as [Rate Year],
a.tkeffdate as [Max Date],
tkrt03 as [Standard Rate]
FROM stageElite.dbo.timerate tr JOIN
stageElite.dbo.timekeep tk
ON tk.tkinit = tr.tkinit
WHERE tr.tkinit = '02672' AND
tr.tkeffdate >= '2014-01-01' AND
tr.tkeffdate < '2015-01-01'
ORDER tr.tkeffdate DESC;
Note that I also fixed your date comparisons and table aliases.

DATEDIFF displaying null values

I have used DATEDIFF to distinguish between when the first unit rate was created and the posting date is when the first transaction of that item was posted.
I have the result that I need , however the DateDiff function gives me NULL values starting date for some rows.
SELECT DISTINCT b.[Entry No_] ,
a.[Starting Date],
b.[Posting Date],
b.[Item No_],
b.[Invoiced Quantity],
a.[Litre Conversion Factor],
a.[Unit Rate] ,
b.[Location Code],
a.[Excise Location],
a.[Excise Type Code],
a.[Unit Of Measure Code]
FROM [Spier Live$Value Entry] b
LEFT JOIN [Transfer Excise Tbl] a
ON a.[No_] = b.[Item No_]
AND b.[Location Code] = a.[Location Code]
AND DateDiff(y,b.[Posting Date],a.[Starting Date]) > -365 --DateDiff Year -365 for starting date
AND DateDiff(y,b.[Posting Date],a.[Starting Date]) < 0 --DateDiff Yer < 0 for posting date
WHERE b.[Posting Date] > '2013-02-26' --This is when the unit rate was entered
AND b.[Gen_ Bus_ Posting Group] IN ('LOCA','EXSA')
AND b.[Invoiced Quantity] <>0 --Removing all zero values
AND b.[Item No_] = 'F00335'
ORDER BY b.[Posting Date]
My Result
Transfer Excise Tbl This is the table I am joining on
As alex points out in the comments, you're looking for things with datediffs based on day of year, not year. Did you mean <= 0, btw? These criteria don't make sense and so probably aren't what you really want. If so, they'd cause joins to fail where you don't really want them to, leading to nulls showing for table a columns.

SQL Calculate Percentage in Group By

I have an SQL query that is used as the basis for a report. The report shows the amount of fuel used grouped by Year, Month and Fuel Type. I would like to calculate the percentage of the total for each fuel type, but I'm not having much luck. In order to calculate the percentage of the whole, I need to be able to get the total amount of fuel used regardless of the group it is in and I can't seem to figure out how to do this. Here is my query:
SELECT Year([DT1].[TransactionDate]) AS [Year], Month([DT1].[TransactionDate]) AS [Month], DT1.FuelType, Format(Sum(DT1.Used),"#.0") AS [Total Used],
FROM (SELECT TransactionDate, FuelType, Round([MeterAfter]-[MeterBefore],2) AS Used FROM FuelLog) AS DT1
WHERE (((DT1.TransactionDate) Between [Start Date] And [End Date]))
GROUP BY Year([DT1].[TransactionDate]), Month([DT1].[TransactionDate]), DT1.FuelType
ORDER BY Year([DT1].[TransactionDate]), Month(DT1.TransactionDate), DT1.FuelType;
I tried adding the following as a subquery but I get an error saying the subquery returns more than one result.
(SELECT Sum(Round([MeterAfter]-[MeterBefore],2)) AS Test
FROM Fuellog
WHERE Year([Year]) and Month([Month])
GROUP BY Year([TransactionDate]), Month([TransactionDate]))
Once I get the total of all fuel I will need to divide the amount of fuel used by the total amount of both fuel types. Should I be approaching this a different way?
Try this
SELECT A.[Year]
,A.[Month]
,A.[FuelType]
,A.[Total Used]
,(A.[Total Used] / B.[Total By Year Month]) * 100 AS Percentage
FROM
(
SELECT Year([DT1].[TransactionDate]) AS [Year]
, Month([DT1].[TransactionDate]) AS [Month]
, DT1.FuelType
, Format(Sum(DT1.Used),"#.0") AS [Total Used]
FROM (
SELECT TransactionDate
, FuelType
, Round([MeterAfter]-[MeterBefore],2) AS Used
FROM FuelLog
) AS DT1
WHERE (((DT1.TransactionDate) Between [Start Date] And [End Date]))
GROUP BY Year([DT1].[TransactionDate]), Month([DT1].[TransactionDate]), DT1.FuelType
ORDER BY Year([DT1].[TransactionDate]), Month(DT1.TransactionDate), DT1.FuelType
) A
INNER JOIN
(
SELECT Sum(Round([MeterAfter]-[MeterBefore],2)) AS [Total By Year Month]
, Year([TransactionDate]) AS [Year]
, Month([TransactionDate])) AS [Month]
FROM Fuellog
GROUP
BY Year([TransactionDate])
, Month([TransactionDate]))
) B
ON A.[Year] = B.[Year]
AND A.[Month] = B.[Month]
You need to join to the totals -- something like this (untested might have typos)
SELECT
Year([DT1].[TransactionDate]) AS [Year],
Month([DT1].[TransactionDate]) AS [Month],
DT1.FuelType,
Format(Sum(DT1.Used),"#.0") AS [Total Used],
(Sum(DT1.Used) / FT.Total) * 100 AS Percent
FROM (
SELECT
TransactionDate,
FuelType,
Round([MeterAfter]-[MeterBefore],2) AS Used
FROM FuelLog
) AS DT1
JOIN (
SELECT
Sum(Round([MeterAfter]-[MeterBefore],2)) AS Total
FuelType
FROM Fuellog
WHERE TransactionDate Between [Start Date] And [End Date]
GROUP BY FuelType
) FT ON DT1.FuelType = FT.FeulType
WHERE DT1.TransactionDate Between [Start Date] And [End Date]
GROUP BY Year([DT1].[TransactionDate]), Month([DT1].[TransactionDate]), DT1.FuelType, FT.Total
ORDER BY Year([DT1].[TransactionDate]), Month(DT1.TransactionDate), DT1.FuelType, FT.Total;

Get the sum() in a WHERE clause

I have this SQL, but it dosen't work correctly.
SELECT [Customer No_], SUM(Amount) AS SumDebitor, [Posting Date]
FROM dbo.[3S Company A_S$Detailed Cust_ Ledg_ Entry]
WHERE ([Posting Date] <= CONVERT(DATETIME, '2015-04-10 00:00:00', 102))
GROUP BY [Customer No_], [Posting Date]
HAVING ([Customer No_] = '45')
What i want, is get the total SUM() of all posts from before my date.
Right now i get more that 5000 results, sum of everyday.
Can someone help me on the right way?
you should not have posting date with grouping (if you do posting date grouping .. you will get all posting date sum independently)
and moreover having clause is not required .. your query should be like following
SELECT [Customer No_], SUM(Amount) AS SumDebitor
FROM dbo.[3S Company A_S$Detailed Cust_ Ledg_ Entry]
WHERE ([Posting Date] <= CONVERT(DATETIME, '2015-04-10 00:00:00', 102))
And ([Customer No_] = '45')
GROUP BY [Customer No_]
or as below (if you need count for all customer)
SELECT [Customer No_], SUM(Amount) AS SumDebitor
FROM dbo.[3S Company A_S$Detailed Cust_ Ledg_ Entry]
WHERE ([Posting Date] <= CONVERT(DATETIME, '2015-04-10 00:00:00', 102))
GROUP BY [Customer No_]