I have to use GROUP BY statement to pull data from SQL Server CE.
Now I'm getting
In aggregate and grouping expressions, the SELECT clause can contain
only aggregates and grouping expressions. [ Select clause = ,Date ]
but I really want to get date.
Query is as follows
SELECT Date
FROM Installments
GROUP BY ID
HAVING Sr = max(Sr)
What am I doing wrong? Please explain
When you use group by, you group by some field, and apply an aggregate function.
So, in the select, you shoud that field (the grouped result) and then the result of the function used.
Maybe you want something like
SELECT Id, Max(date) FROM Installments GROUP BY ID
It will depends on what you want.
Read about Group by here
If you are grouping by ID, then each group could potentially have multiple different dates, so you can't select Date. You could, for example,
select Max(Date) FROM Installments GROUP BY ID
As it says, you need to include the columns you're returning in the group by clause.
SELECT Date FROM Installments GROUP BY ID, Date
I suspect what you may be trying to do is this
SELECT Date
FROM Installments
WHERE sr = (Select MAX(sr) from Installments)
Related
This is my error
ORDER BY items must appear in the select list if SELECT DISTINCT is specified.
This is my subquery
(select TOP(1) Error from tablename v, tablename j where v.columname= j.columnname1 ORDER BY v.columnname,j.columnname1)
I'm confused because I am using an order by clause, any idea's?
Thank you in advance
Never use commas in the FROM clause. Always use proper, explicit, standard, readable JOIN syntax.
you can fix the problem using GROUP BY. This allows you to use aggregation functions on columns in the ORDER BY:
select TOP (1) Error
from tablename v join
tablename j
on v.columname = j.columnname1
group by Error
order by max(v.columnname), max(j.columnname1);
In my experience, this is normally used for date/time columns to order something by the most recent time it appeared.
I’m working on a project which is an online shop,
I want to show in a page the most sold items,
So my sql is
Select (*), Count(Product_ID) as n from Order_Details order by n desc.
But it doesn’t work. Can someone help?
You need to aggregate the data first, this can be done using the GROUP BY clause:
SELECT (*), COUNT(DISTINCT Product_ID)
FROM table
GROUP BY Product_ID
ORDER BY COUNT(DISTINCT Product_ID) DESC
The DESC keyword allows you to show the highest count first, ORDER BY by default orders in ascending order which would show the lowest count first.
SELECT (*), Max(DISTINCT Product_ID)
FROM table
GROUP BY Product_ID
ORDER BY Max(DISTINCT Product_ID) DESC
the most sold item you use max
I want to create a SQL query that will do the counting for me instead of in the razor code, I want to calculate the amount of distinct dates in my database.
I found that SQL Server CE does not support count(distinct column_name) and instead using group by would be the solution, but for some reason I could not make it work, what am I doing wrong?
SELECT COUNT(date) as date
FROM Test
GROUP BY date
This simply counted every date in my database and not the distinct ones when writing it out like the following
var totalcount = 0;
foreach (var c in db.Query(query))
{
var ttotalcount = c.date;
totalcount += ttotalcount;
}
<a>#totalcount<a>
Updated
Your query is asking for the counts of each distinct date. If you want to know how many of those you have you need to sum them up. You can do this be nesting your query with a SUM query. Then use an additional column defulted to "1", to allow to sum up the number of rows (which should be your distinct dates). Also date can be a reserved word. You might want to try and avoid using that as a column name.
SELECT SUM(New_Row) as dateSUM from (
SELECT COUNT(date) as dateCount, 1 as New_Row FROM Test GROUP BY date
) a
Maybe:
SELECT COUNT(date) as [date]
FROM Test
GROUP BY date
Date is a reserved word, need to add []
You are confusing SQL with the three usages of date. I am assuming that the original field is named date. I am also assuming that each record has the date field populated.
SELECT COUNT(*) as numDates FROM Test GROUP BY date
I'm trying to make a ratings system. I'm using visual studio. The database has 2 tables, one table for all the music tracks, and another table containing the ratings, and is hooked up with an FK.
Here's my tables and columns
http://i.gyazo.com/fc5d042749c8c04fb2b9aa2b64831b0a.png
This is my current attempt and it's giving me an error
SELECT DISTINCT Track.TrackId, SUM(Ratings.rating) AS average, Track.Name, Ratings.trackid
FROM Track
INNER JOIN Ratings
ON Track.TrackId = Ratings.trackid
Msg 8120, Level 16, State 1, Line 1
Column 'Track.TrackId' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.
Every time you are using either a sum, avr, min or max, etc. functions you have to use Group by that is the law..
What you need to do first is SUM the ratings by track and then joining those later with your track table, something like this:
SELECT T.TrackId, SUM(R.rating) AS average, T.Name
FROM Track T
INNER JOIN
(SELECT TrackId, SUM(Ratings.rating) AS average
FROM Ratings Group By TrackId ) R
ON T.TrackId = r.TrackId
If you want to use aggregation functions, then you generally want a group by. Without the group by, the query will return only one row.
SELECT t.TrackId, SUM(r.rating) AS average, t.Name
FROM Track t INNER JOIN
Ratings r
ON t.TrackId = r.trackid
GROUP BY t.TrackId, t.name;
In addition, I made the following changes:
Removed distinct from the select. This is almost never needed for an aggregation query.
Added table aliases that are abbreviations of the table names, to make the query more readable.
Removed Ratings.TrackId from the select statement. It is redundant, because it is the same as Track.TrackId.
Added a group by statement.
Don't use distinct. It doesn't do the same thing as Group By.
In SQL-think, what you're trying to do is group all the rows by Trackid, and average the rating in each group which you do like this:
SELECT Track.TrackId, AVG(1.0000 * Ratings.rating) AS average
FROM Track
JOIN Ratings ON Track.TrackId = Ratings.trackid
Group By Track.TrackId
But, you're also trying to pick up the Name at the same time. Doing that at that same time as a group by isn't as straightforward in SQL as you might wish. A 'correct' way is something like:
SELECT
Track.TrackId,
Average,
Name
FROM Track
INNER JOIN (
SELECT TrackId, AVG(1.0000 * Ratings.rating) AS average
FROM Ratings
Group By TrackId
) R
ON Track.TrackId = R.trackid
I have a List of UserID's and a open connection to SQL Server. How can I loop through this List and Select matching UserID with First_Name and Last_Name columns? I assume the output can be in a datatable?
many thanks
It varies slightly depending on which type of SQL you're running, but this and this should get you started.
The most expedient way of doing this would be to:
Turn the List into a string containing a comma separated list of the userid values
Supply that CSV string into an IN clause, like:
SELECT u.first_name,
u.last_name
FROM USER_TABLE u
WHERE u.userid IN ([comma separated list of userids])
Otherwise, you could insert the values into a temp table and join to the users table:
SELECT u.first_name,
u.last_name
FROM USER_TABLE u
JOIN #userlist ul ON ul.userid = u.userid
Write a function in your SQL database named ParseIntegerArray. This should convert a comma delimited string into a table of IDs, you can then join to this in your query. This also helps to avoid any SQL injection risk you could get from concatenating strings to build SQL. You can also use this function when working with LINQ to SQL or LINQ to Entities.
DECLARE #itemIds nvarchar(max)
SET itemIds = '1,2,3'
SELECT
i.*
FROM
dbo.Item AS i
INNER JOIN dbo.ParseIntegerArray(#itemIds) AS id ON i.ItemId = id.Id
This article should help you: http://msdn.microsoft.com/en-us/library/aa496058%28SQL.80%29.aspx
I've used this in the past to create a stored procedure accepting a single comma delimited varchar parameter.
My source from the C# program was a checked list box, and I built the comma delimited string using a foreach loop and a StringBuilder to do the concatenation. There might be better methods, depending on the number of items you have in your list though.
To come back to the SQL part, the fn_Split function discussed in the article, enables you to transform the comma delimited string back to a table variable that SQL Server can understand... and which you can query in your stored procedure.
Here is an example:
CREATE PROCEDURE GetSelectedItems
(
#SelectedItemsID Varchar(MAX) -- comma-separated string containing the items to select
)
AS
SELECT * FROM Items
WHERE ItemID IN (SELECT Value FROM dbo.fn_Split(#SelectedItemsIDs,','))
RETURN
GO
Note that you could also use an inner join, instead of the IN() if you prefer.
If you don't have the fn_Split UDF on your SQL Server, you can find it here: http://odetocode.com/Articles/365.aspx
I hope this helps.