Group by 4 different levels and total numeric field - sql

I'm querying a financial database that has the following information:
Company ID
Fiscal Year
Fiscal Period
Account
Amount
I want to group the data by the first four fields and show a grouped total of amount.
I tried the GROUP BY but that doesn't seem to work.
In my screenshot, I'm trying to get rows 1-10 to show as one line, as all the information is the same except for the amount.
Here's my code:
SELECT Erp.GLJrnDtl.Company, Erp.GLJrnDtl.FiscalYear,
Erp.GLJrnDtl.FiscalPeriod, Erp.GLJrnDtl.BalanceAcct,
Erp.GLJrnDtl.BookDebitAmount - Erp.GLJrnDtl.BookCreditAmount AS Amount
FROM Erp.GLJrnDtl INNER JOIN
Erp.GLPeriodBal ON Erp.GLJrnDtl.Company =
Erp.GLPeriodBal.Company AND Erp.GLJrnDtl.FiscalYear =
Erp.GLPeriodBal.FiscalYear AND Erp.GLJrnDtl.FiscalPeriod =
Erp.GLPeriodBal.FiscalPeriod AND
Erp.GLJrnDtl.BalanceAcct =
Erp.GLPeriodBal.BalanceAcct
WHERE (Erp.GLJrnDtl.FiscalYear >= 2018) AND (Erp.GLJrnDtl.Company
= N'011') and (Erp.GLJrnDtl.SegValue1 = N'310050')
GROUP BY Erp.GLJrnDtl.Company, Erp.GLJrnDtl.FiscalYear,
Erp.GLJrnDtl.FiscalPeriod, Erp.GLJrnDtl.BalanceAcct,
Erp.GLJrnDtl.PostedDate, Erp.GLJrnDtl.BookDebitAmount,
Erp.GLJrnDtl.BookCreditAmount, Erp.GLJrnDtl.SegValue1,
Erp.GLPeriodBal.BalanceAmt

select company_id, fiscal_year, fiscal_period, account, sum(amount)
from table group by company_id, fiscal_year, fiscal_period, account
You need to leave out the field you want to aggregate outside the group by line

Please explain why this does not do what you want:
select Company_ID, Fiscal_Year, Fiscal_Period, Account, sum(Amount)
from t
group by Company_ID, Fiscal_Year, Fiscal_Period, Account;
This is the "obvious" query. The query in the image is much more complicated.

Related

In SQL, how to you join multiple aggregate queries (count or sum specifically)?

I have a table that has the total number of different items per person. I am trying to create a new table that counts the number of people with a total of 0, 1, 2, 3, 4, 5, 6, and 7+ items grouped by company and year. I think I have individual queries that accomplish this task, but I can't get a join to work in order to fill the new table. The individual queries that seem to accomplish what I am trying to do are:
SELECT
Company,
YEAR(Date) as Year,
COUNT(*) as items0_Count
FROM table
WHERE items_total = 0
GROUP BY Company, YEAR(Date)
ORDER BY Company, YEAR(Date)
SELECT
Company,
YEAR(Date) as Year,
COUNT(*) as items1_Count
FROM table
WHERE items_total = 1
GROUP BY Company, YEAR(Date)
ORDER BY Company, YEAR(Date)
I would obviously have that same query 8 times with only the where statement changing in order to generate the counts for each case, but only included two here to keep the question short. Hope this makes sense, and thank you in advance for your help!
Use conditional aggregation:
SELECT Company, YEAR(Date) as Year,
SUM(CASE WHEN items_total = 0 THEN 1 ELSE 0 END) as items0_Count,
SUM(CASE WHEN items_total = 1 THEN 1 ELSE 0 END) as items2_Count
FROM table
GROUP BY Company, YEAR(Date)
ORDER BY Company, YEAR(Date);
You can add additional columns for whatever item counts you want.
Union all/ union the two queries you have. You'll get the desired else follow #GordonLinoff's answer.
Also as an easy way try this below
SELECT
Company,
YEAR(Date) as Year,
COUNT(*) as items0_Count
FROM table
WHERE items_total in (1,0)
GROUP BY Company, YEAR(Date)
ORDER BY Company, YEAR(Date)

Add group by to Oracle Query and get an error

Error after add group by and aggregation functions
This query runs good without group by and aggregate functions. After I add group by and aggregate function, it give me this error. I am a starter for query. Any advance will be helpful. The company is using Netsuite as the ERP system. Netsuite is using Oracle database. I am using ODBC connecting to their data base.
Select to_number(to_char(Transactions.trandate, 'YYYY')) as Year,
to_number(to_char(Transactions.trandate, 'MM')) as Month,
NVL(Parent.name, Entity.name) as Customer,
Case
When Upper(Substr(Replace(Items.name,'.',''),1,4)) IN ('MEAL', 'BASE', 'BOLT', 'BITE', 'FUEL')
THEN Upper(Substr(Replace(Items.name,'.',''),1,4))
ELSE Items.name
END as Item,
Accounts.type_name as Account,
-sum(Transaction_lines.amount) as Sales
From Transactions
Left Join Transaction_lines ON Transactions.transaction_id=Transaction_lines.Transaction_id
Left Join Items ON Transaction_lines.item_id=Items.item_id
Left Join Accounts ON Transaction_lines.account_id=Accounts.account_id
Left Join Entity ON Transactions.entity_id=Entity.entity_id
Left Join Entity as Parent on Entity.parent_id=Parent.entity_id
Where transactions.trandate >= '2013-1-1'
and Transactions.transaction_type IN ('Invoice', 'Item Fulfillment', 'Cash Sale')
and Accounts.type_name IN ('Income', 'Expense', 'Cost of Goods Sold')
Group By
to_number(to_char(Transactions.trandate, 'YYYY')),
to_number(to_char(Transactions.trandate, 'MM')),
NVL(Parent.name, Entity.name),
Case
When Upper(Substr(Replace(Items.name,'.',''),1,4)) IN ('MEAL', 'BASE', 'BOLT', 'BITE', 'FUEL')
THEN Upper(Substr(Replace(Items.name,'.',''),1,4))
ELSE Items.name
END,
Accounts.type_name
Order By Year, Month, Customer, Item, Account
You say your query without GROUP BY works.
Then take advantage of your alias.
SELECT Year, Month, Customer, Item, Account, -sum(Amount) as Sales
FROM (
YOUR WORKING QUERY
) T
GROUP BY Year, Month, Customer, Item, Account
Order By Year, Month, Customer, Item, Account

Revenue year by year SQL Server query

I have the following query which provides me with the item and item details, values, rate and quantity across each location.
I am trying to get the yearly revenue based on the Start and End Date. Example, if the chosen date was 2013-2015. The final result will create 3 columns one for 2013 revenue, one for 2014 revenue and one for 2015 revenue.
I am a newbie and still not an expert in writing queries, but here is what I have currently:
SELECT
department,
item,
itemdesc,
qty1,
qty2,
rate_1,
rate_2,
SUM(mm.days*mm.rate*mm.qty)
FROM
items it
LEFT JOIN
(SELECT
i.days, i.rate, i.days, ii.todate, ii.itemid
FROM
invoiceofitems ii
JOIN
invoices i on i.id = ii.id
WHERE
ii.todate BETWEEN #StartDate and #EndDate) mm ON mm.itemid = it.itemid
GROUP BY
department,
item,
itemdesc,
qty1, qty2,
rate_1, rate_2
ORDER BY
item
However, this does not provide me with a year to year aggregation of invoice revenue that I require.
I know this is possible to achieve via iterating through this. But how would I accomplish this and where would I start on this?
Would I need to know the start and end date of each year and iterate through that and then add a counter to the year until year= EndDate?
I'm extremely confused. Help would be appreciated.
I hope that PIVOT and YEAR help you to solve this problem (some columns are omitted):
;WITH SRC(department,item, ... , rate_2, yr, calculation) AS
(SELECT it.department, it.item, ..., it.rate_2, YEAR(ii.todate) as yr,
(i.days * i.rate *i.qty) as calculation
FROM items it
LEFT JOIN invoiceofitems ii ON ii.itemid = it.itemid
JOIN invoices i ON i.id = ii.id)
SELECT department,item, ..., [2013],[2014],[2015]
FROM SRC
PIVOT
(SUM(calculation) FOR yr IN ([2013],[2014],[2015])) PVT
The YEAR function returns only 'year' part of your date and makes grouping easier. PIVOT just rotates grouped data from rows to columns.

SQL Summary of revenues by region (in ranked order from highest to lowest, calculate % of total for each region)

Summary of revenues by region (in ranked order from highest to lowest, calculate % of total for each region). Basically, I am trying to write a query that will show the revenues of each region relative to the total revenue.
I am using SQL in Microsoft Access.
My table has the following columns: ID, Region, Revenue
There are 3 regions: West, Central, East
Heres what I have so far:
SELECT Region, Sum(Revenue) AS TotalRevenue
FROM Sales
GROUP BY Region
ORDER BY Sum(Revenue) DESC
Any help would be greatly appreciated
Try this:
SELECT Region, SUM(Revenue) AS TotalRevenue,
(SUM(Revenue)/(SELECT Sum(Revenue) FROM Sales)) AS percentage
FROM Sales
GROUP BY Region
ORDER BY Sum(Revenue) DESC
This is one way that I'd offer, for only three regions its really overkill, but it should work.
SELECT Region, Sum(Revenue) AS TotalRevenue, Sum(Revenue)/x.allRegionRevenue
FROM Sales s,
inner join (select sum(revenue) allRegionRevenue)) x
on s.revenue*0 = x.allRegionRevenue*0
GROUP BY Region
ORDER BY Sum(Revenue) DESC
*Edit: * Modified this a bit as Access doesn't support actual "cross join" syntax, but I think we can "fake" it with an inner join on a condition that's always true - klugey trick here is merely to multiply references from each to zero forcing all recs to match. Hope this helps.

adding a calculated/virtual column to an existing query

My query returns a sales column total for each month and a purchases total for each month, for certain categories.
SELECT theMonth,
sum(Sales) as sumSales,
sum(Saleswotax) as sumSaleswotax,
sum(Purchases) as sumPurchases,
sum(Purchaseswotax) as sumPurchaseswotax
FROM ( SELECT date_format(saledate, '%Y-%m') AS theMonth,
sales.cost as Sales,
ROUND(sales.cost*0.85, 2) AS Saleswotax,
0 AS Purchases,
0 AS Purchaseswotax
FROM sales, products
WHERE sales.product = products.name
AND category='Food'
UNION ALL
SELECT date_format(purchasedate, '%Y-%m') AS theMonth,
0 as Sales,
0 AS Saleswotax,
purchases.cost as Purchases,
ROUND(purchases.cost*0.85, 2) AS Purchaseswotax,
FROM purchases) AS all_costs
group by theMonth
I am trying to return a column(that does not actually exist in the table) in my query that is just a calculation of an existing table., ie the saleswotax and purchaseswotax columns.
I am using a function, and returning it AS a name...why is it not working?
In the union, you used 0 as sales and purchases columns, but didn't also do that for -wotax columns. They need to match up for the union to work properly (I think you know that, since you did it for Sales and Purchases).
You need to remove the comma after AS Purchasewotax in the latter half of the UNION:
SELECT theMonth,
sum(Sales) as sumSales,
sum(Saleswotax) as sumSaleswotax,
sum(Purchases) as sumPurchases,
sum(Purchaseswotax) as sumPurchaseswotax
FROM ( SELECT date_format(saledate, '%Y-%m') AS theMonth,
sales.cost as Sales,
ROUND(sales.cost*0.85, 2) AS Saleswotax,
0 AS Purchases,
0 AS Purchaseswotax
FROM sales, products
WHERE sales.product = products.name
AND category='Food'
UNION ALL
SELECT date_format(purchasedate, '%Y-%m') AS theMonth,
0 as Sales,
0 AS Saleswotax,
purchases.cost as Purchases,
ROUND(purchases.cost*0.85, 2) AS Purchaseswotax
FROM purchases) AS all_costs
GROUP BY theMonth
Last time when I saw, there was no declarative support for computed fields in MySQL.
You would have to either add computed columns to your table and fill them using an UPDATE/INSERT trigger. Or create Views with additional computed columns.