Add group by to Oracle Query and get an error - sql

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

Related

How to calculate AVG into left join between 2 tables?

I have to calculate the avg of gross revenue on bigquery (the key is item_id).
SELECT
t0.order_create_date AS day,
t0.site_country AS country,
p0.product_brand AS brand,
p0.product_gender AS gender,
p0.product_department AS department,
t0.item_qty AS items_sold,
t0.item_sale_price AS gross_revenue,
t0.item_net_price AS net_revenue,
FROM
`transactions` t0
LEFT JOIN
`products` p0
ON
t0.item_id = p0.item_id
ORDER BY
country,
day ASC
I tried this :
SELECT
t0.order_create_date AS day,
t0.site_country AS country,
p0.product_brand AS brand,
p0.product_gender AS gender,
p0.product_department AS department,
t0.item_qty AS items_sold,
t0.item_sale_price AS gross_revenue,
AVG(t0.item_sale_price) AS average_value,
t0.item_net_price AS net_revenue,
FROM
`transactions` t0
LEFT JOIN
`products` p0
ON
t0.item_id = p0.item_id
ORDER BY
country,
day ASC
Biquery result:
SELECT list expression references t0.order_create_date which is neither grouped nor aggregated at [2:3]
The problem is that you didn't aggregate or by all the other columns, except the average_value one. Here you can read more about Group By.
From the names of the columns you are creating, I suppose you also want to have other information such as gross and net revenue. You would have to use some aggregate function on them too, otherwise the error would continue.
Something like the following should probably work:
SELECT
t0.order_create_date AS day,
t0.site_country AS country,
p0.product_brand AS brand,
p0.product_gender AS gender,
p0.product_department AS department,
sum(t0.item_qty) AS items_sold,
sum(t0.item_sale_price) AS gross_revenue,
AVG(t0.item_sale_price) AS average_value,
sum(t0.item_net_price) AS net_revenue,
FROM
transactions t0
LEFT JOIN
products p0
ON
t0.item_id = p0.item_id
GROUP BY
day,
country,
brand,
gender,
department
ORDER BY
country,
day ASC

Group by 4 different levels and total numeric field

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.

I want to fetch this data year wise

Select
CIDetail.Itemname,
sum(CIDetail.TaxAmount+ CIDetail.LineAmount) As [TotalAmount]
From
CIDetail (Nolock)
INNER JOIN CIHeader On CIDetail.InvoiceNo= CIHeader.InvoiceNo
Where
CIHeader.InvoiceDate Between '2010-04-01' AND '2014-04-01'
Group By
CIDetail.Itemname
Have a derived table where you use ANSI SQL's EXTRACT to get the year part out of the date, and also add the amounts together. At main level you do GROUP BY both Itemname and year:
Select Itemname, "year", SUM(Amount) as TotalAmount
from
(
CIDetail.Itemname,
extract(year from CIHeader.InvoiceDate) as "year",
CIDetail.TaxAmount + CIDetail.LineAmount As Amount
From
CIDetail (Nolock)
INNER JOIN CIHeader On CIDetail.InvoiceNo= CIHeader.InvoiceNo
) dt
Group By
Itemname, "year"
No dbms tagged in question, but if your dbms doesn't support EXTRACT, try YEAR(CIHeader.InvoiceDate) for example, or something else.
Add to the query a order by clause. Here as you are saying that you want it by date, I will assume that one itemname has only one InvoiceDate. And thus its max will have the same value. You will have to do it as follows
Select CIDetail.Itemname,
sum(CIDetail.TaxAmount+ CIDetail.LineAmount) As [TotalAmount],
From CIDetail (Nolock) INNER JOIN CIHeader
On CIDetail.InvoiceNo= CIHeader.InvoiceNo
Where CIHeader.InvoiceDate Between '2010-04-01' AND '2014-04-01' Group By
CIDetail.Itemname
Order By max(CIHeader.InvoiceDate) ASC

how to get both month name and year from field and by w

I have to fetch both month name and year from field in my table but writing below query I am getting an error. Kindly do the needful to rectify my error.
Thanks in advance.
Query:
select SUM(p.Actual_Amount) as buying,
SUM(p.TotalPackageCost) as selling,
(SUM(p.TotalPackageCost) - SUM(p.Actual_Amount)) as profit,
COUNT(e.Enquiry_Id) as Sales,
DATENAME(MM,e.Arrives_On) as Month,
(DATENAME(MONTH,e.Arrives_On) +'-'+ DATENAME(YYYY,e.Arrives_On)) as Date
from Pricing p
inner join Enquiry e on e.Enquiry_Id = p.Enquiry_Id where e.Agent_Name ='Ish Travels' and e.status = 'Confirmed By Company'
group by DATENAME(MM,e.Arrives_On)
order by Month desc
But I am getting the error:
Column 'Enquiry.Arrives_On' is invalid in the select list because it
is not contained in either an aggregate function or the GROUP BY
clause.
Please help me to resolve the error.
Your group by clause is not complete. Every expression in your projection which is not contained in an aggregate function has to be used in group by. I'm pretty sure this is working:
select
SUM(p.Actual_Amount) as buying,
SUM(p.TotalPackageCost) as selling,
(SUM(p.TotalPackageCost) - SUM(p.Actual_Amount)) as profit,
COUNT(e.Enquiry_Id) as Sales,
DATENAME(MM,e.Arrives_On) as Month,
(DATENAME(MONTH,e.Arrives_On) +'-'+ DATENAME(YYYY,e.Arrives_On)) as Date
from
Pricing p inner join Enquiry e on e.Enquiry_Id = p.Enquiry_Id
where
e.Agent_Name ='Ish Travels'
and
e.status = 'Confirmed By Company'
group by
DATENAME(MM,e.Arrives_On),
(DATENAME(MONTH,e.Arrives_On) +'-'+ DATENAME(YYYY,e.Arrives_On))
order by
5 desc

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.