Trouble making a running sum in Access query - sql

I'm stuck trying to get a running sum to work in an Access query.
I've been playing around with various Dsum expressions, but they all have resulted in errors.
Basically, I have two columns, one with a year, one with a count of parts for that year, and I would like the third to be a running sum of the part count over the years.
My SQL for the first two columns looks like this:
SELECT DatePart("yyyy",[EoL]) AS AYear, Count(EquipmentQuery.Equipment) AS EquipCount
FROM EquipmentQuery
GROUP BY DatePart("yyyy",[EoL])
ORDER BY DatePart("yyyy",[EoL]);
Any suggestions on how to get the third column to work as a running sum?
Thanks for the help!

If you create a report, there is a property to calculate a running sum.
If you prefer a query, you can use a subquery to calculate the running sum:
SELECT DatePart("yyyy",[EoL]) AS AYear
, Count(eq1.Equipment) AS EquipCount
, (
SELECT Count(eq2.Equipment)
FROM EquipmentQuery eq2
WHERE DatePart("yyyy",eq2.[EoL]) <= DatePart("yyyy",eq1.[EoL])
) AS RunningSuma
FROM EquipmentQuery AS eq1
GROUP BY
DatePart("yyyy",[EoL])
ORDER BY
DatePart("yyyy",[EoL]);

try the following code:
SELECT Year([EQ1].[EOL]) AS Yr,
Sum(IIf(Year([EQ2].[eol])=Year([EQ1].[eol]),1,0)) AS [current],
Sum(IIf(Year([EQ2].[eol])<=Year([EQ1].[eol]),1,0)) AS [cumulative]
FROM [equipmentquery] AS EQ1, [equipmentquery] AS [EQ2]
GROUP BY Year([EQ1].[EOL]);
ansd if you want running totals instead of counts:
SELECT Year([EQ1].[EOL]) AS Yr,
Sum(IIf(Year([EQ2].[eol])=Year([EQ1].[eol]),[EQ2].equipment,0)) AS [current],
Sum(IIf(Year([EQ2].[eol])<=Year([EQ1].[eol]),[EQ2].equipment,0)) AS [cumulative]
FROM [equipmentquery] AS EQ1, [equipmentquery] AS [EQ2]
GROUP BY Year([EQ1].[EOL]);

Related

How to SUM two different Amount_Eur from two different Type_Trans columns SQL

Here is the table:
SELECT
*
FROM
Fact_Transactions;
Here is my code to only select two columns as an example:
SELECT
type_trans,
SUM(Amount_Eur) AS Total_Ins
FROM
fact_transactions
WHERE
type_trans IN ('CARD-INCOMING', 'BANK-INCOMING')
GROUP BY
type_trans;
Now, I want to `SUM`` the total.
Thanks in advance!
I tried to sum two amounts from different columns (Card-Incoming and Bank-Incoming)
I tried to reproduce the scenario in my environment
IN SQL there is a CUBE function
The CUBE operator generates multiple grouping sets inside a GROUP BY.
CUBE generates subtotals across all column combinations specified in GROUP BY.
Code Example:
SELECT
coalesce([Type_T rans],'Total') as [Type_T rans],
SUM(Amount_Eur) AS Total_Ins
FROM
fact_transactions
WHERE
[Type_T rans] IN ('CARD-INCOMING', 'BANK-INCOMING')
GROUP BY CUBE ([Type_T rans]);
Output:

SQL Sum Total with multiple assignments

select dc_id, whse_id, assg_id, START_DTIM,
UNIT_SHIP_CSE*prod_cub as TOTAL_CUBE
from exehoust.aseld
I attached a photo to show how the query currently populates. I want to sum the TOTAL_CUBE for each distinct ASSG_ID. I have tried case where sum and group by but keep failing. Basically want to do a SUM IF for each distinct ASSG_ID
You need to group by the assg_id, but ou need also the define what happens to all the other columns i choose MIN only to give you a hint, you need to choose the function yourself
select MIN(dc_id), MIN(whse_id), assg_id, MIN(START_DTIM),
SUM(UNIT_SHIP_CSE*prod_cub) as TOTAL_CUBE
from exehoust.aseld
GROUP BY assg_id
use select assg_id, sum() over(partition by assg_id order by assg_id) to sum by groupings

counts' division doesn't work in full code

I do have a problem with a task because my division value is different when I use it alone and when I use it in full code. Let's say I do this code:
SELECT (count(paimta))::numeric / count(distinct paimta) as average
FROM Stud.Egzempliorius;
and finally a number I get is 2.(6)7, but when I use it in full code which is:
SELECT Stud.Egzempliorius.Paimta, COUNT(PAIMTA) as PaimtaKnyga
FROM Stud.Skaitytojas, Stud.Egzempliorius
WHERE Stud.Skaitytojas.Nr=Stud.Egzempliorius.Skaitytojas
GROUP BY Stud.Egzempliorius.Paimta
HAVING count(paimta) > (count(paimta))::numeric / count(distinct paimta);
it's value changes because division is not working anymore and let's say instead of having
HAVING count(paimta) > (count(paimta))::numeric / count(distinct paimta);
my codes turns into
HAVING count(paimta) > (count(paimta))::numeric;
and these values are equal, so I can't get final answer. That's database I use https://klevas.mif.vu.lt/~baronas/dbvs/biblio/show-table.php?table=Stud.Egzempliorius
I was struggling for 10 hours now and finally I've lost my patience... So, my question is what I have to do that this code:
SELECT (count(paimta))::numeric / count(distinct paimta) as average
FROM Stud.Egzempliorius;
value doesn't change in full code?
Picture how it changes Photo
Your solution fails because the two queries operate on a different groups of rows. The first query does a computation over the whole dataset, while the second one groups by paimta.
One option would have been to use window functions, but as far as concerns Postgres does not support count(distinct) as a window function.
I think that the simplest approach is to use a subquery :
select e.paimta, count(paimta) as paimtaknyga
from stud.skaitytojas s
inner join stud.egzempliorius e on s.nr = e.skaitytojas
group by e.paimta
having count(paimta) > (
select (count(paimta))::numeric / count(distinct paimta) from stud.egzempliorius
)

Grouping a percentage calculation in postgres/redshift

I keep running in to the same problem over and over again, hoping someone can help...
I have a large table with a category column that has 28 entries for donkey breed, then I'm counting two specific values grouped by each of those categories in subqueries like this:
WITH totaldonkeys AS (
SELECT donkeybreed,
COUNT(*) AS total
FROM donkeytable1
GROUP BY donkeybreed
)
,
sickdonkeys AS (
SELECT donkeybreed,
COUNT(*) AS totalsick
FROM donkeytable1
JOIN donkeyhealth on donkeytable1.donkeyid = donkeyhealth.donkeyid
WHERE donkeyhealth.sick IS TRUE
GROUP BY donkeybreed
)
,
It's my goal to end up with a table that has primarily the percentage of sick donkeys for each breed but I always end up struggling like hell with the problem of not being able to group by without using an aggregate function which I cannot do here:
SELECT (CAST(sickdonkeys.totalsick AS float) / totaldonkeys.total) * 100 AS percentsick,
totaldonkeys.donkeybreed
FROM totaldonkeys, sickdonkeys
GROUP BY totaldonkeys.donkeybreed
When I run this I end up with 28 results for each breed of donkey, one correct I believe but obviously hundreds of useless datapoints.
I know I'm probably being really dumb here but I keep hitting in to this same problem again and again with new donkeydata, I should obviously be structuring the whole thing a new way because you just can't do this final query without an aggregate function, I think I must be missing something significant.
You can easily count the proportion that are sick in the donkeyhealth table
SELECT d.donkeybreed,
AVG( (dh.sick)::int ) AS proportion_sick
FROM donkeytable1 d JOIN
donkeyhealth dh
ON d.donkeyid = dh.donkeyid
GROUP BY d.donkeybreed

Total Count in Grouped TSQL Query

I have an performance heavy query, that filters out many unwanted records based on data in other tables etc.
I am averaging a column, and also returning the count for each average group. This is all working fine.
However, I would also like to include the percentage of the TOTAL count.
Is there any way of getting this total count without rerunning the whole query, or increasing the performance load significantly?
I would also prefer if I didn't need to completely restructure the sub query (e.g. by getting the total count outside of it), but can do if necessary.
SELECT
data.EquipmentId,
AVG(MeasureValue) AS AverageValue,
COUNT(data.*) AS BinCount
COUNT(data.*)/ ???TotalCount??? AS BinCountPercentage
FROM
(SELECT * FROM MultipleTablesWithJoins) data
GROUP BY data.EquipmentId
See Window functions.
SELECT
data.EquipmentId,
AVG(MeasureValue) AS AverageValue,
COUNT(*) AS BinCount,
COUNT(*)/ cast (cnt as float) AS BinCountPercentage
FROM
(SELECT *,
-- Here is total count of records
count(*) over() cnt
FROM MultipleTablesWithJoins) data
GROUP BY data.EquipmentId, cnt
EDIT: forgot to actually divide the numbers.
Another approach:
with data as
(
SELECT * FROM MultipleTablesWithJoins
)
,grand as
(
select count(*) as cnt from data
)
SELECT
data.EquipmentId,
AVG(MeasureValue) AS AverageValue,
COUNT(data.*) AS BinCount
COUNT(data.*)/ grand.cnt AS BinCountPercentage
FROM data cross join grand
GROUP BY data.EquipmentId