During executing the query below the following message comes:
Msg 130, Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
SELECT DATEADD(n,-10,[TimeStampLocalSystem]) as Date,
AVG(CASE WHEN [Minute10Average]>0 THEN [Minute10Average] END) AS Average,
AVG(CASE WHEN ABS(1-Minute10Average/AVG(CASE WHEN [Minute10Average]>0 THEN [Minute10Average] END))<0.5 THEN Minute10Average END) AS Average_corr
FROM [XXX]
INNER JOIN [XXX]
ON [XXX].Systemnumber=[YYY].SystemNumber
WHERE [TimeStampLocalSystem] BETWEEN '2022-09-16 17:10:00' AND '2022-09-16 18:20:00'
AND [DataPointID] IN (XXX)
AND RIGHT(FORMAT([TimeStampLocalSystem],'DD.MM.YYYY hh:mm:ss'),4) = '0:00'
GROUP BY [TimeStampLocalSystem]
The problem is in the line:
AVG(CASE WHEN ABS(1-Minute10Average/AVG(CASE WHEN [Minute10Average]>0 THEN [Minute10Average] END))<0.5 THEN Minute10Average END) AS Average_corr
Could you help me to define what is wrong?
Use Having and the aggregate filter.
select name, sum(field) from table group by name having sum(field)>1
Related
Helo!
How I make the following syntax of postgresql in SQL server without create subquery
PGSQL:
SELECT
COUNT(*) AS "QUANTIDADE TOTAL",
COUNT(*) FILTER(WHERE SEXO = 'Masculino') AS "MASCULINO"
FROM FUNCIONARIOS;
I tried but got an error:
Message 156, Level 15, State 1, Line 4
Incorrect syntax next to 'WHERE' keyword.
Try
SELECT COUNT(x) as [Quantudate Total],
SUM (CASE WHEN SEXO = 'Masculino' THEN 1
ELSE 0
END) AS MASCULINO
FROM FUNCIONARIOS
For better performance always better to use one specific field in the aggregate function than using a , eg use COUNT(id) than COUNT()
Conditional aggregation would work...
SELECT
COUNT(*) AS "QUANTIDADE TOTAL",
SUM(case when SEXO = 'Masculino' then 1 end) AS "MASCULINO"
FROM FUNCIONARIOS;
I'm using the following query, I need to show Grand Total count but it is throwing error like
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.
SELECT
ISNULL(OQ.GroupID,'') GroupName,
CONVERT(VARCHAR, ISNULL(COUNT(CASE WHEN RequestStatusKey IN ( 1, 2 ) THEN OrderRecordID END), 0)) TotalRecord,
SUM(COUNT(CASE WHEN RequestStatusKey IN ( 1, 2 ) THEN OrderRecordID END)) AS GrandTotal
FROM dbo.tblDesk OQ
WHERE OQ.RequestStatusKey IN ( 1, 2 )
AND OQ.OrderTypeKey <> 1
AND OQ.GroupID IS NOT NULL
GROUP BY OQ.GroupID
ORDER BY OQ.GroupID
I just need to Grand total.
As the error message suggests, you can not use aggregate function inside another aggregate function.
For your query to achieve SUM of OrderRecordId when RequestStatusKey IN (1,2) you can use SUM without using COUNT like this:
SUM(CASE WHEN RequestStatusKey IN (1,2) THEN 1 ELSE 0 END) AS GrandTotal
However, as Tim suggested, since you have already used RequestStatusKey IN (1,2) in your WHERE clause you don't need to use conditional SUM. Just use COUNT without condition:
COUNT(OrderRecordId) AS GrandTotal
UPDATE:
Since you want to show sum of the all rows count in the same result, you can use ROLLUP for that:
SELECT
ISNULL(OQ.GroupID,'Grand Total') GroupName,
CONVERT(VARCHAR, COUNT(OrderRecordID)) TotalRecord
FROM tblDesk OQ
WHERE OQ.RequestStatusKey IN ( 1, 2 )
AND OQ.GroupID IS NOT NULL
GROUP BY ROLLUP (OQ.GroupID)
ORDER BY OQ.GroupID
See this SQLFiddle.
I am getting the following error
"ORA-00923: FROM keyword not found where expected" while executing the query
SELECT
count(pf.pref_selection) filter ( WHERE pc.collection = "players") OVER (partition BY pc.collection,pc.user_id ) AS Avg_players
count(pf.pref_selection) filter ( WHERE pc.collection = "teams") OVER (partition BY pc.collection,pc.user_id ) AS Avg_teams
FROM NBA_OWNER.PREFERENCES pf
inner join NBA_OWNER.PREF_COLLECTIONS pc on pc.ID=pf.COLLECTION_ID
where pc.LAST_UPDATE_DATE>"30-SEP-16'`
You have several errors. As #cricket_007 pointed put you are missing a comma between the two count expressions. But you also have invalid syntax with your filter clause - which doesn't exist, at least in Oracle; you have used double quotes around string literals instead of single quotes; the quotes around your date string are even odder; and you are relying on NLS settings for the date format.
This is closer to what you need, if I understand what you were attempting:
SELECT
count(case when pc.collection = 'players' then pf.pref_selection end)
OVER (partition BY pc.user_id) AS Avg_players,
count(case when pc.collection = 'teams' then pf.pref_selection end)
OVER (partition BY pc.user_id) AS Avg_teams
FROM NBA_OWNER.PREFERENCES pf
inner join NBA_OWNER.PREF_COLLECTIONS pc on pc.ID=pf.COLLECTION_ID
where pc.LAST_UPDATE_DATE > date '2016-09-30'
The output might not be very useful though. For each user ID you may get multiple rows, each showing the total count (which you've called avg for some reason). You probably only want to see the counts for each ID once, and to see which ID they relate to, so I think you want an aggregate rather than analytic count:
SELECT
pc.user_id,
count(case when pc.collection = 'players' then pf.pref_selection end)
AS Avg_players,
count(case when pc.collection = 'teams' then pf.pref_selection end)
AS Avg_teams
FROM NBA_OWNER.PREFERENCES pf
inner join NBA_OWNER.PREF_COLLECTIONS pc on pc.ID=pf.COLLECTION_ID
where pc.LAST_UPDATE_DATE > date '2016-09-30'
group by pc.user_id
I have a table with the schema as shown below:
CREATE TABLE Table1 (`membertype` varchar(1));
INSERT INTO Table1 (`membertype`)
VALUES
('Y'),('H'),('U'),('W'),('W'),('W'),('H'),('H'),('U'),
('U'),('P'),('P'),(''),('P'),('P'),('P'),(''),('W'),
('Y'),('Y'),('Y'),('H'),('D'),('D'),('D'),('D'),('H'),
('W'),('W');
What I am trying to achieve is to get the count of each type in the column and also their percentage to the total number of types in the column.
I tested the below query in MYSQL and got the desired result:
select (case when m.membertype='Y' then 'Young Adult'
when m.membertype='H' then 'Head'
when m.membertype='W' then 'Spouse'
when m.membertype='P' then 'Aged Parent'
when m.membertype='U' then 'Unknown'
when m.membertype='D' then 'Deceased' else 'No Match' end) as type,
count(*) as typecount,
count(*)/t.total*100 as percentage from Table1 as m,
(select count(*) as total from Table1) as t group by membertype;
type typecount percentage
No Match 2 6.8966
Deceased 4 13.7931
Head 5 17.2414
Aged Parent 5 17.2414
Unknown 3 10.3448
Spouse 6 20.6897
Young Adult 4 13.7931
**
Link
**
The same query fails in HIVE with the below error:
select (case when h.member='Y' then 'Young Adult'
when h.member='H' then 'Head'
when h.member='W' then 'Spouse'
when h.member='P' then 'Aged Parent'
when h.member='U' then 'Unknown'
when h.member='D' then 'Deceased' else 'No Match' end) as type,
count(*) as typecount,
count(*)/t.total*100 as percentage from hhinfo as h,
(select count(*) as total from hhinfo) as t group by member;
FAILED: SemanticException [Error 10025]: Line 1:277 Expression not in GROUP BY key 'total'
What am I missing here? Any help would be appreciated.
Try to explicitly add total to the group by clause
...as t group by member, total
I need help with a query. Consider the following table:
I need to select first the sum of each Code from table. I am doing it with simple sum and group by statement. Then I have to subtract the results from each code sum where type='r'
1) Say for first part of query, we will get 2 rows from SUM (one with total USD and one with total YEN)
2) Now I need to subtract from these results the corresponding USD, YEN value which has Type='r'
I have to do it inside SQL and not a stored procedure.
Why not use a WHERE statement to say WHERE Type != 'r' so that those values never even get added to sum in the first place...
SELECT `Code`, SUM(`Amount`) AS `Total`
FROM `Table`
WHERE `Type` != 'r'
GROUP
BY `Code`;
Something like that.
select code, l.amount - r.amount
from
(select code, sum(amount) as amount from my_table group by code) l
left join (select code, sum(amount) as amount from my_table where type = 'r' group by code) r
on l.code = r.code
You can do this in a single, simple query:
select
code,
sum(case when type = 'r' then (-1 * amount) else amount end) as sum
from
yourtable
group by
code
Basically, you're changing the sign of the rows that have type = 'r', so when you sum all rows for a particular code you'll get the correct answer.
Does it have to be a single query?
I'd say SUM the total, then SUM the subcategory where Type='r', then subtract one from the other.
You could do this in one line of SQL, but I'm pretty sure it would be either joining the table with itself or using a subquery. Either way, it's doing the same amount of work as the above.
Try:
select code,
sum(amount) gross_total,
sum(case when type = 'r' then amount else 0 end) type_r_total,
sum(case when type != 'r' then amount else 0 end) net_total
from yourtable
group by code;
to see the overall totals, type R only totals and non-type R totals for each currency on one row per currency, in a single pass.