Question

Hello i have a table with columns:

saled qty, item no, no
-3, 1996-s, 149
-2, 1996-s, 150
-2, 1968-b, 151

Now i should get the top sold products. Maybe i have to group somehow by item no and then sort by saled qty and then i could select top 3 for example?

Update: There are also other columns that i don't need but becuase of them i get error:

timestamp' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause.

Almost there

SELECT TOP(3) [Item No_], SUM([Invoiced Quantity]) as [qty] 
FROM 
    [Demo Database NAV (7 - 1)].[dbo].[CRONUS (Schweiz) AG$Value Entry]
GROUP BY 
    [Item No_]
HAVING [Item Ledger Entry Type] = 1
ORDER BY 
    SUM([Invoiced Quantity]) DESC

gives error: Item Ledger Entry Type' is invalid in the HAVING clause because it is not contained in either an aggregate function or the GROUP BY clause.

Was it helpful?

Solution

SELECT TOP(3) 
    item_no, 
    SUM(saled qty) 
FROM 
    TABLENAME 
GROUP BY 
    item_no, [Item Ledger Entry Type]
HAVING [Item Ledger Entry Type] = 1
ORDER BY 
    SUM(saled qty) DESC

or

SELECT TOP(3) 
    item_no, 
    SUM(saled qty) 
FROM 
    TABLENAME 
WHERE [Item Ledger Entry Type] = 1
GROUP BY 
    item_no
ORDER BY 
    SUM(saled qty) DESC

Depending on if you want pre or post aggregation filtering

Just replace 3 with whatever number of products you want.

Explanation: When you do a group by you can only include columns in your result which are either part of the group by clause OR are being aggregated in some way. Here I've used SUM which aggregates the saled_qty column and I've ommited all the other columns from your query.

The best way to think of this is to imagine you yourself rather than SQL were grouping the data.... Say we group by item_no... how are you meant to know what to do with all the saled_qty values? You will have multiple values of saled_qty for each row of your results (One row per whatever is in your grouping clause... in this case item_no). SQL will not allow you to be ambiguous about this and so throws an error.

OTHER TIPS

It would work:

SELECT TOP 3 * FROM tbl GroupBy item_no ORDER BY saled_qty DESC
SELECT saledqty,itemno, no
FROM Table1
WHERE saledqty IN (
SELECT TOP 3 MAX(saledqty) As Sale
FROM Table1
SELECT TOP 3 * FROM table GroupBy itemno ORDER BY saledqty DESC

Update:

If you need to select other columns too, then include them in your GroupBy Clause also.

For Example:

  SELECT TOP 3 count(itemno),itemno,timestamp FROM table GroupBy itemno,timestamp ORDER BY saledqty DESC
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top