Group Data Within Query - sql

I wrote this query and the results are not being grouped. They are appearing as such:
Facility | Posting Month | Account Type | Amount
-------------------------------------------------
Name | July | Debit Adj. | 100
Name | July | Credit Adj. | -200
Name | July | Debit Adj. | 150
Name | July | Credit Adj. | -150
-------------------------------------------------
The results I am trying to get is the Posting month to appear once for the Debit Adj. and Credit Adj. type and the respective total amounts. Total of $250 for Debits and -$350 for credits. Thanks for the help!
SELECT pw.Facility, DATENAME(mm, pw.[Posting Date]) AS [Posting Month],
lc.[Gl Account Type], sum(pw.[Tx Amt]) AS Amount
FROM DBO.PaymentWOLedger AS pw
JOIN DBO.LedgerCodeTable AS lc
ON lc.[Description] = pw.[Tx Desc]
WHERE lc.[Gl Account Type] = 'Credit Adjustment (Write Off)' OR
lc.[GlAccount Type] = 'Debit Adjustment (CWO)'
GROUP BY pw.[Posting Date], pw.Facility, lc.[Gl Account Type]
ORDER BY pw.Facility, pw.[Posting Date]

Use Month instead of Date in Group by & Order by
GROUP BY DATENAME(mm, pw.[Posting Date]), pw.Facility, lc.[Gl Account Type]
ORDER BY pw.Facility, DATENAME(mm, pw.[Posting Date])
currently the data is grouped on each date since you have used pw.[Posting Date] in Group by which has date/month/year part in it.

Related

Hello , currently learning and I am in need of some assistance. I need to write a query that will return a table with select columns [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
Write a query that will return a table with the following columns:
User ID, Site ID, User Name, Total Sales, Total Refunds, Net Amount Collected
I need to write a query that will return a table which at the moment im trying to figure out thanks.
Tried select statement but failed.enter image description here
I agree with the others that simply handing this over will not help your learning much. There are a bunch of concepts that you need to learn here. Submitting this answer for your homework might be awkward (and result in a score of 0) if you can't explain it!
Common Table Expressions
Aggregate Functions
Outer Joins
with cte_sales as
(
select
t.[User Id],
t.[Site Id],
sum(t.Amount) as [Total Sales]
from Transactions t
where t.[Transaction Type] = 'Sale'
group by t.[User Id],
t.[Site Id]
),
cte_refunds as
(
select
t.[User Id],
t.[Site Id],
sum(t.Amount) as [Total Refunds]
from Transactions t
where t.[Transaction Type] = 'Refund'
group by t.[User Id],
t.[Site Id]
)
select
u.[User Id],
u.[Site Id],
u.[Name] as [User Name],
coalesce(s.[Total Sales],0) as [Total Sales],
abs(coalesce(r.[Total Refunds],0)) as [Total Refunds],
(coalesce(s.[Total Sales],0) + coalesce(r.[Total Refunds],0)) as [Net Amount Collected]
from Users u
left join cte_sales s on s.[User Id] = u.[User Id]
and s.[Site Id] = u.[Site Id]
left join cte_refunds r on r.[User Id] = u.[User Id]
and r.[Site Id] = u.[Site Id]
order by u.[User Id],
u.[Site Id];
Demo
| User Id | Site Id | User Name | Total Sales | Total Refunds | Net Amount Collected |
|---------|---------|-----------|-------------|---------------|----------------------|
| 1 | 1 | Arthur | 120 | 120 | 0 |
| 2 | 1 | Aaron | 90 | 30 | 60 |
| 2 | 2 | Brett | 90 | 0 | 90 |

Using multiple columns to determine SUM results

I am having trouble getting my head around the following sum. I have a table of items, which shows the location, the item code and the size code. The unique feature of this table is there is a flag that determines whether the location will stock a particular item.
I have another table that shows the stock movements of the items. This table also shows location, item, size and either a positive or negative entry. The sum of the positive/negative entries give the current stock holding.
What i can't seem to do is say SUM the stock movement quantities where the item and size are marked with 'location can stock this item'
The first select statement brings back items that can be stocked by location
select
S.[Location Code],S.[Item No_],S.[size],
from [Stockkeeping Units] S
where [Range in Location] = 1
The results return a list as:
location Code| Item no | Size
1 | SHIRT1 | s
1 | SHIRT1 | m
1 | SHIRT2 | s
1 | SHIRT2 | m
2 | SHIRT1 | s
2 | SHIRT2 | m
The second select statement bring back the current stock for an item by location
select
L.[Location Code],L.[Item No_],L.[size],
sum(L.[Quantity]) as Quantity
from [Item Ledger Entry] L
location Code| Item no | Size | Quantity
1 | SHIRT1 | s | 5
1 | SHIRT1 | m | 3
1 | SHIRT2 | s | 5
1 | SHIRT2 | m | 7
2 | SHIRT1 | s | 3
2 | SHIRT2 | m | 0
It is when i try to join these tables to bring back the combination of the first 2 select statements, that it goes astray
select L.[Location Code],L.[Item No_], L.[Variant Code],
sum(L.[Quantity]) as Quantity
from [$Item Ledger Entry] L
join [Stockkeeping Unit] on [Item Ledger Entry].[Item No] = [Stockkeeping
Unit].[Item No_]
where [Stockkeeping Unit].[Range in Location] = 1
group by L.[Location Code],L.[Item No_],L.[Variant Code]
What i would like to see is:
location|item no|size|quantity where range in location is yes
The joined query is bringing back result the are ignoring the
[Stockkeeping Unit].[Range in Location] = 1 request
The joined query is also not returning the same SUM results as the second SELECT query
It looks like you meant this:
SELECT [Location Code], [Item No_], [size], SUM([Quantity]) AS Quantity
FROM [Item Ledger Entry] L
WHERE EXISTS (
SELECT *
FROM [Stockkeeping Units] S
WHERE S.[Range in Location]=1
AND S.[Location code]=L.[Location code]
AND S.[Item No]=L.[Item no]
AND S.[Size]=L.[Size]
)
GROUP BY L.[Location Code], L.[Item No_], L.[size];

Access Query - Sum of Field based on newest for each day

I have the following data:
Site # | Site Name | Product | Reading Date | Volume
1 | Cambridge | Regular | 02/21/17 08:00 | 40000
2 | Cambridge | Regular | 02/22/17 07:00 | 35000
3 | Cambridge | Regular | 02/22/17 10:00 | 30000
What I want to achieve is get the SUM of [Volume] of the last 30 days while taking the newest reading EACH day possible since its pretty inconsistent whether one day there are 1,2 or 3 readings. I have tried a couple of things but can't get it to work.
This is what I've tried:
SELECT [Site #], Product, Sum(Volume) AS SumOfVolume, DatePart("d",InventoryDate]) AS Day
FROM [Circle K New]
GROUP BY [Site #], Product, Day
HAVING (([Site #]=852446) AND (Product ="Diesel Lows"))
ORDER BY DatePart("d",[Inventory Date]) DESC;
Result:
It adds the two readings of the same day. I was/am thinking about just getting a daily average then finding the monthly average from that. But I'm unsure if the value changes affect average numbers.
Based on your description:
select sum(volume)
from data as d
where d.readingdate in (select min(d2.readingdate)
from data as d2
group by int(d2.readingdate)
) and
d.readingdate >= dateadd("d", -30, date());

MS Access show data of only 30 days

I'm struggling to create a query to get data from two tables where it needs to only show data of a sales rep for the first 30 days from the sales rep start date. Here are my tables.
Sales Rep Table
|ID | Name | Start Date|
Second Table would be all the sales of all the reps
|Order Date | Order Number | Sales Amount | REP ID |
I know you can Join and group by ID and get the total amount, but I only need the amount within the first 30 days of a reps start date.
Any help would be appreciated. I hope this makes sense?
Thanks
Join on Rep ID and apply a filter:
where [Order Date] Between [Start Date] and DateAdd("m", 1, [Start Date])

SQL statement using WHERE from a GROUP or RANK (part 2)

I recently posted a question about a SQL Where Statement/Grouping here:
SQL statement using WHERE from a GROUP or RANK
Now I've got somewhat of a follow-up.
So similar to the previous question, let's assume I have a table of say 35,000 rows with these columns:
Sales Rep | Parent Account ID| Account ID | Total Contract Value | Date
Each row is individual by account id but multiple account IDs can fall under a parent account ID.
Similar to the responses on the first question, this is probably going to be a table w/i a table. So first, everything has to be grouped by Sales Rep. From that, everything needs to be grouped by Parent Account ID where the grouped total contract value of all the accounts is >= 10,000. Then everything will be displayed and ranked by the total TCV of the Parent account ID and I need the top 35 Parent account IDs by agent.
So the first couple of lines of data may look like this:
Sales Rep | Parent Account ID| Account ID | Total Contract Value | Date | Rank
John Doe | ParentABC12345 | ABC425 | 5,000 | 1/2/2013 |1
John Doe | ParentABC12345 | ABC426 | 10,000 | 1/2/2013 |1
John Doe | ParentDJE12345 | DJE523 | 11,000 | 1/2/2013 |2
John Doe | ParentFBC12345 | FBC6723 | 4,000 | 1/2/2013 |3
John Doe | ParentFBC12345 | FBC6727 | 4,000 | 1/2/2013 |3
Notice how the ranking works based off of the parent Account ID. The account ID DJE523 has the single greatest TCV but it's ranked second b/c the grouped value of parent account ID ParentABC12345 is greater. So there would be a ranking of 35 parent account IDs but in that ranking their could be say 100+ lines of actual data.
Any thoughts?
Always nice to follow up. The "parent rank" is added as an INNER JOIN.
Edit: As correctly mentioned by Dan Bracuk, my first answer was not correct. I altered the query to meet the correct conditions. I also applied the timespan to the Parent Account's.
DECLARE #minimumValue decimal(20,2) = 10000
DECLARE #numberOfAccounts int = 35
DECLARE #from datetime = '1/1/2013'
DECLARE #till datetime = DATEADD(MONTH, 1, #from)
SELECT
[sub].[Sales Rep],
[sub].[Rank],
[sub].[Account ID],
[sub].[Total Contract Value],
[sub].[Parent Account ID],
[sub].[Total],
[sub].[ParentRank]
FROM
(
SELECT
[s].[Sales Rep],
[s].[Account ID],
[s].[Total Contract Value],
DENSE_RANK() OVER (PARTITION BY [s].[Sales Rep] ORDER BY [s].[Total Contract Value] DESC) AS [Rank],
[p].[Parent Account ID],
[p].[Total],
[p].[ParentRank]
FROM [Sales] [s]
INNER JOIN
(
SELECT
[Parent Account ID],
SUM([Total Contract Value]) AS [Total],
RANK() OVER(ORDER BY SUM([Total Contract Value]) DESC) AS [ParentRank]
FROM [Sales]
WHERE[Date] > #from AND [Date] < #till
GROUP BY [Parent Account ID]
HAVING SUM([Total Contract Value]) > #minimumValue
) AS [p] ON [s].[Parent Account ID] = [p].[Parent Account ID]
WHERE [Date] > #from AND [Date] < #till
) AS [sub]
WHERE [sub].[Rank] <= #numberOfAccounts
ORDER BY
[Sales Rep] ASC,
[ParentRank] ASC,
[Rank] ASC
And here is a new Fiddle.
I think this will do it for you, if you're using SQL Server:
Select top 35
SalesRep,
ParentAccountId,
sum(TotalContractValue) from Table
group by SalesRep, ParentAccountId
order by sum(TotalContractValue) desc