Anthony
Anthony

Reputation: 811

Using SQL CASE Statement to replace Text with GROUP BY

I am Using SQL Server and i have the following Problem and i am hopping someone could help me.

I am getting this Error

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

I do not want to include Text in the GROUP BY Clause yes that makes the query run but the issue is there is other text in the field i do not want it grouping by i would just like to replace the Name with the Text for items matching the CASE

when i add Text to the group by i get this result.

           43036    SPECIAL     73.0000
           43036    SPECIAL     6.0000

Upvotes: 0

Views: 489

Answers (1)

Gurwinder Singh
Gurwinder Singh

Reputation: 39457

Issue is exactly what the error says. You are selecting TransactionsLine.text which is not in the group by clause.

you probably want to put the case in your group by clause:

select StockItemCode as CODE,
    (
        case 
            when StockItems.Description like 'item%'
                then TransactionsLine.text
            else StockItems.Description
            end
        ) as name,
    SUM(ItemQuantity) as Sales
from Transactions
inner join TransactionsLine on Transactions.id = TransactionsLine.TransactionID
inner join StockItems on TransactionsLine.StockItemID = StockItems.id
where location = @location
    and Department = 43
    and Transactions.date between @FROM
        and @TO
    and TransactionTypeID in (3, 32)
group by StockItemCode,
    case 
        when StockItems.Description like 'item%'
            then TransactionsLine.text
        else StockItems.Description
        end

Upvotes: 2

Related Questions