I have a stored procedure in which i am trying to select all the columns of a table Table 1. There is another table which uses Table1 primary key as foreign key. I want to count number of records in this foreign key table with that select like this:
SELECT *, count(*) VacancyCount FROM Table1 hc LEFT JOIN Table2 hv on hc.CompanyID = hv.CompanyID WHERE hc.Deleted = 0 group by hc.CompanyID ORDER BY NameLang1
but it gives error:
Column 'dbo.Table1.NameLang1' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Please suggest how to fix this?
You can use the SQL SELECT statement with the COUNT() function to select and display the count of rows in a table of a database.
In SQL, you can make a database query and use the COUNT function to get the number of rows for a particular group in the table. Here is the basic syntax: SELECT COUNT(column_name) FROM table_name; COUNT(column_name) will not include NULL values as part of the count.
Counting all of the Rows in a Table. To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.
Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).
Please try:
select *, (select COUNT(*) from Table2 hv where hv.CompanyID=hc.CompanyID) VacancyCount from Table1 hc where hc.Deleted = 0 order by hc.NameLang1, VacancyCount desc
for ordering using the new column
select * from( select *, CONVERT(NVARCHAR(100), (select COUNT(*) from Table2 hv where hv.CompanyID=hc.CompanyID)) VacancyCount from Table1 hc where hc.Deleted = 0 )x Order by CASE WHEN @OrderByParam = 1 THEN NameLang1 ELSE VacancyCount END
Provided column NameLang1
and VacancyCount
are of same datatype.
You're doing grouping wrong. You need to use all the columns from Table 1 in SELECT instead of '*' and in GROUP BY clause as well.
Or you can try a different approach like this:
SELECT * FROM Table1 hc LEFT JOIN (SELECT CompanyID, COUNT(*) cnt FROM Table2 GROUP BY CompanyID) hv on hc.CompanyID = hv.CompanyID WHERE hc.Deleted = 0 ORDER BY NameLang1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With