Add two values resulting from a SUM() as a new column - sql

I've got the following query:
SELECT
permit_id,
SUM(poc_emissions) AS POC_emissions,
SUM(non_poc_emissions) AS NON_POC_emissions
FROM
( .... SUBQUERY ...) main
GROUP BY
permit_id
What I need to do now is to add the values from POC_emissions and NON_POC_emissions into a new column called let's say TOTAL.
I tried:
SELECT
permit_id,
SUM(poc_emissions) AS POC_emissions,
SUM(non_poc_emissions) AS NON_POC_emissions,
(POC_emissions + NON_POC_emissions) AS Total
FROM
( .... SUBQUERY ...) main
GROUP BY
permit_id
but it gives me an error.
Any suggestions?
Thanks

Query:
SELECT permit_id,
Sum(poc_emissions) AS Totle_Poc_emissions,
Sum(non_poc_emissions) AS Total_Non_poc_emissions,
(Sum(poc_emissions) + Sum(non_poc_emissions)) AS total
FROM ( .... subquery ...) main
GROUP BY permit_id
Reason:
You can not use new aliases Totle_Poc_emissions and Total_Non_poc_emissions you gave as a sql query follows an order of execution, which implies FROM and GROUP BY happen before SELECT. So your GROUP BY won't know what the new aliases are as SELECT will happen afterwards, it will just know the column names.

Related

using subquery's column alias as a property in main query

i want to know if the main query can see the alias, here's an example:
SELECT AVG(values)
FROM(
SELECT SUM(a1) AS values
FROM tableX
)
Does the first query see the alias "values"?
Does the first query see the alias "values"?
Yes, it does. The subquery creates a derived table, and aliases act as column names in that context. However, standard SQL requires that you give an alias to the subquery.
So:
SELECT AVG(vals)
FROM(
SELECT SUM(a1) AS vals
FROM tableX
) t --> alias of the subquery
Side notes:
values is a language keyword, hence not a good choice for a column name; I renamed it to vals in the query
Your example is really contrived; the subquery always returns one row, so aggregating again in the outer query makes little sense: this is guaranteed to return the same value as that of the subquery. A more useful example would put a group by clause in the subquery, like so
SELECT AVG(vals)
FROM(
SELECT SUM(a1) AS vals
FROM tableX
GROUP BY id
) t

Use 'COUNT(*) OVER() AS' in postgres while selecting items from a table

I am doing a selection on a table, but also need the count of the items. Apparently I have to use window functions but can't get it work.
I am doing a simple select query and want to count how many entries are there, so something like:
SELECT * FROM "myTable"
COUNT(*) OVER() AS total
WHERE name='John Doe';
This is not working and I am getting the following error: ERROR: ERROR: syntax error at or near "COUNT" LINE 2: COUNT(*) OVER(name) AS _total
How do I use the window functions to count my entries in a table while doing a query? Am I way off base here?
The COUNT(*) is a column in the SELECT:
SELECT t.*, COUNT(*) OVER() AS total
FROM "myTable" t
WHERE name = 'John Doe';
The FROM clause follows the SELECT clause and ends the definitions of the columns in the result set.

SQL query - count with subquery

I want to get the count of all the columns that are retrieved in the query.I have used the below code:
select count (*)
from (
select distinct ID,salary,name,location
from test
) ;
I am getting an error message:
Incorrect error at ; expecting AS,ID or quoted_ID
When I add as below:
select count (*)
from (
select distinct ID,salary,name,location
from test
) as count;
The query works now but the column name is not renamed to the alias given. What is the logic behind this?
In Sql you have to give alias to subquery. So that's the reason the second query works and first one fails
i don't know what you are trying to achieve but to correct this would be
select count (*) from (select distinct ID,salary,name,location from test ) as myTAble;
subquery will act as your table to query from therefore it needs a
name or alias
You are giving alias to the table and not column. The following query would work.
select count (*) As count
from (
select distinct ID,salary,name,location
from test
) as tbl;

Using the DISTINCT keyword causes this error: not a SELECTed expression

I have a query that looks something like this:
SELECT DISTINCT share.rooms
FROM Shares share
left join share.rooms.buildingAdditions.buildings.buildingInfoses as bi
... //where clause omitted
ORDER BY share.rooms.floors.floorOrder, share.rooms.roomNumber,
share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent
Which results in the following exception:
Caused by: org.hibernate.exception.SQLGrammarException: ORA-01791: not a SELECTed expression
If I remove the DISTINCT keyword, the query runs without issue. If I remove the order by clause, the query runs without issue. Unfortunately, I can't seem to get the ordered result set without duplicates.
You are trying to order your result with columns that are not being calculated. This wouldn't be a problem if you didn't have the DISTINCT there, but since your query is basically grouping only by share.rooms column, how can it order that result set with other columns that can have multiple values for the same share.rooms one?
This post is a little old but one thing I did to get around this error is wrap the query and just apply the order by on the outside like so.
SELECT COL
FROM (
SELECT DISTINCT COL, ORDER_BY_COL
FROM TABLE
// ADD JOINS, WHERE CLAUSES, ETC.
)
ORDER BY ORDER_BY_COL;
Hope this helps :)
When using DISTINCT in a query that has an ORDER BY you must select all the columns you've used in the ORDER BY statement:
SELECT DISTINCT share.rooms.floors.floorOrder, share.rooms.roomNumber,
share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent
...
ORDER BY share.rooms.floors.floorOrder, share.rooms.roomNumber,
share.rooms.firstEffectiveAt, share.shareNumber, share.sharePercent

Average when meeting where clause

I want to find the average amount of a field where it meets a criterion. It is embedded in a big table but I would like this average field in there instead of doing it in a separate table.
This is what I have so far:
Select....
Avg( (currbal) where (select * from table
where ament2 in ('r1','r2'))
From table
If you want to AVG only a subset of a query use case when ... then to replace value in non-matching rows with null as nulls are ignored by avg().
Select id,
sum(something) SomethingSummed,
avg(case when ament2 in ('r1','r2') then currbal end) CurrbalAveragedForR1R2
From [table]
group by id
You can put all the other sums which you want to be embedded into the AVG statement, inside the table reference inside the FROM clause. Something like:
SELECT AVG(currbal)
FROM
(
SELECT * -- other sums
FROM table
WHERE ament2 IN ('r1','r2')
) t
You can write a full sub-select into the select list:
SELECT ...,
(SELECT AVG(Currbal) FROM Table WHERE ament2 IN ('r1', 'r2')) AS avg_currbal,
...
FROM ...
Whether that will do exactly what you want depends on a number of things. You might need to make that into a correlated subquery; assuming 'ament2' is in Table, it is not a correlated sub-query at the moment.