SQL select invalid because it is not contained in aggregate function - sql

Here's the problem, I want to display the month, count and avg of one column in a table, but I keep getting an error when I try and group it by the month.
This is the code:
SELECT MONTH(ContractDate) AS Q,
DATENAME(month, ContractDate) AS M,
COUNT(ContractDate) AS C, SUM(ContractPrice) AS S
FROM dashboard
WHERE YEAR(ContractDate) = $year
AND ContractDate IS NOT NULL
AND ContractPrice IS NOT NULL
GROUP BY MONTH(ContractDate)
But this results in the error:
[Microsoft][SQL Server Native Client 10.0][SQL Server]
Column 'dashboard.ContractDate' is invalid in the select
list because it is not contained in either an aggregate
function or the GROUP BY clause.
But if I removed the MONTH() from the group by... it works fine.. But I need to have them grouped by month otherwise I get multiple of the same month not counted as one.
Sorry again, I did search and there is HEAPS of answers, but like I said I'm noob and they didn't really help me because I don't understand why this happens.

You have to have all columns that are not aggregates in the GROUP BY. Either add your DATENAME column into the GROUP BY or remove it from the query altogether.
GROUP BY MONTH(ContractDate) AS Q, DATENAME(month, ContractDate)

Try executing your query after removing DATENAME(month, ContractDate) AS M. I guess this is causing the issue. You are doing a GROUP BY MONTH(ContractDate) but also trying to use ContractDate which is not in the GROUP BY list.

Related

Access: GROUP BY with IIf() condition

I'm trying to run the following Code in Access:
SELECT T_SAP_IST.month, SUM(T_SAP_IST.value), IIf([description]="hours","hours","nonhours") AS descr
FROM T_SAP_IST
GROUP BY month, descr
My goal is to get the sum of all values for every month divided into "hours" and "nonhours". However, I get an error which says "'IIf([description]="hours","hours","nonhours")' is not part of an aggregate function"
How can I fix this? Thanks for your help!
In MS Access, you need to repeat the expression:
SELECT T_SAP_IST.month, SUM(T_SAP_IST.value),
IIf([description]="hours","hours","nonhours") AS descr
FROM T_SAP_IST
GROUP BY month, IIf([description] = "hours", "hours", "nonhours");
You can also use a subquery, so you don't have to repeat the expression. MS Access does not support column aliases in the GROUP BY.

Not a group by function at a cumulative query

I'm making a cumulative query, which shows the evolution of clients in my database. To get these query, I use the year and the week of year they joined in the client database.
I have following query to search for relevant data:
SELECT DD.CAL_YEAR, DD.WEEK_OF_YEAR, SUM(COUNT(DISTINCT FAB.ID)) OVER ( ORDER BY DD.CAL_DATE ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW ) AS "Number of account statements"
FROM CLIENT_DATABASE FAB
JOIN DIM_DATE DD ON FAB.BALANCE_DATE_ID = DD.ID
GROUP BY DD.CAL_YEAR, DD.WEEK_OF_YEAR;
But when I compile this query, I get following error:
Error: ORA-00979: not a GROUP BY expression
SQLState: 42000 ErrorCode: 979
How can I fix this?
Since you are grouping by DD.CAL_YEAR, DD.WEEK_OF_YEAR, you can't use DD.CAL_DATE in the order by clause of your cumulative sum function.
It's hard for me to say exactly what you are trying to do without fully understanding your data. But, logically, it does seem like you should be able to simply use DD.CAL_YEAR, DD.WEEK_OF_YEAR in the order by clause instead of DD.CAL_DATE, and still get the results the way you are expecting.
So something like this:
SUM(COUNT(DISTINCT FAB.ID)) OVER ( ORDER BY D.CAL_YEAR, DD.WEEK_OF_YEAR ...

how make query about some of a field are equal?

I'm trying the code below
SELECT Sum(Price) FROM Faktor WHERE date=date
but it shows total of all price. I want to show the sum of per day like:
date ----- sum
2015/5/1 12345
2015/5/2 54124
I have tried below code too but get error:
SELECT date,Sum(Price) FROM Faktor WHERE date=date
[Err] 42000 - [SQL Server]Column 'Faktor.date' is invalid in the
select list because it is not contained in either an aggregate
function or the GROUP BY clause.
Try
SELECT [date],SUM([Price])
FROM Faktor
GROUP BY [date]
Not sure why you'd use date=date, so I left it out.
Just as the error message tells you, you need to use a group by clause and the date column needs to be in it.
SELECT date, SUM(Price)
FROM Faktor
WHERE date=date -- this looks a bit odd... maybe you want a range of dates or something?
GROUP BY date
With SQL Server all non-aggregated columns from the select statement needs to be grouped (unlike some versions of MySQL for instance).
SELECT
date
,SUM(Price)
FROM
Faktor
WHERE
--add date rules here if you have date criteria i.e. date >= 'someDate'
GROUP BY
date

Cannot Group by Year

Beginner SQL Question:
I'm trying to do a group by, by year and I'm getting funny results. I am using SQL Server 2008.
First, I tried
select count(applicationkey) , approveddate from ida.applications group by approveddate
To get a count of applications by date. However, I am interested in applications by year in stead of day so I tried
select count(applicationkey) , approveddate from ida.applications group by year(approveddate)
When I do this, I get an error message -Column 'ida.applications.ApprovedDate' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.-
However, if I do this I get results
select count(applicationkey) from ida.applications group by year(approveddate)
I get results. Its just I want to be able to see what year matches to which count, which I cannot do for some reason. Does anyone know why I am having this problem?
select count(applicationkey),
year(approveddate)
from ida.applications
group by year(approveddate)
group by must match fields in select if not using an aggregate.
You have all the correct parts there, just include the year(approveddate) in your select like so
select count(applicationkey), year(approveddate)
from ida.applications
group by year(approveddate)
In a group query, columns selected have to be aggregate functions or appear in the group-by list, because otherwise SQL wouldn't know which of the multiple values for the column in the group to use.
You can fix your query easily by using
select count(applicationkey) , year(approveddate)
from ida.applications group by year(approveddate)
-- the year displayed is from the group by list

Group by in t-sql not displaying single result

See the image below. I have a table, tbl_AccountTransaction in which I have 10 rows. The lower most table having columsn AccountTransactionId, AgreementId an so on. Now what i want is to get a single row, that is sum of all amount of the agreement id. Say here I have agreement id =23 but when I ran my query its giving me two rows instead of single column, since there is nano or microsecond difference in between the time of insertion.
So i need a way that will give me row 1550 | 23 | 2011-03-21
Update
I have update my query to this
SELECT Sum(Amount) as Amount,AgreementID, StatementDate
FROM tbl_AccountTranscation
Where TranscationDate is null
GROUP BY AgreementID,Convert(date,StatementDate,101)
but still getting the same error
Msg 8120, Level 16, State 1, Line 1
Column 'tbl_AccountTranscation.StatementDate' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Your group by clause is in error
group by agreementid, convert(date,statementdate,101)
This makes it group by the date (without time) of the statementdate column. Whereas the original is grouping by the statementdate (including time) then for each row of the output, applying the stripping of time information.
To be clear, you weren't supposed to change the SELECT clause
SELECT Sum(Amount) as Amount,AgreementID, Convert(date,StatementDate,101)
FROM tbl_AccountTranscation
Where TranscationDate is null
GROUP BY AgreementID,Convert(date,StatementDate,101)
Because you have a Group By StatementDate.
In your example you have 2 StatementDates:
2011-03-21 14:38:59.470
2011-03-21 14:38:59.487
Change your query in the Group by section instead of StatementDate to be:
Convert(Date, StatementDate, 101)
Have you tried to
Group by (Convert(date,...)
instead of the StatementDate
You are close. You need to combine your two approaches. This should do it:
SELECT Sum(Amount) as Amount,AgreementID, Convert(date,StatementDate,101)
FROM tbl_AccountTranscation
Where TranscationDate is null
GROUP BY AgreementID,Convert(date,StatementDate,101)
If you never need the time, the perhaps you need to change the datatype, so you don't have to do alot of unnecessary converting in most queries. SQL Server 2008 has a date datatype that doesn't include the time. In earlier versions you could add an additional date column that is automatically generated to strip out the time companent so all the dates are like the format of '2011-01-01 00:00:00:000' then you can do date comparisons directly having only had to do the conversion once. This would allow you to have both the actual datetime and just the date.
You should group by DATEPART(..., StatementDate)
Ref: http://msdn.microsoft.com/en-us/library/ms174420.aspx