使用SQL CASE语句将Text替换为GROUP BY

时间:2017-02-12 11:28:18

标签: sql sql-server sql-server-2008

我正在使用SQL Server,我遇到了以下问题,我正在跳跃,有人可以帮助我。

我收到此错误

optional_auth_token

我不想在GROUP BY子句中包含Text,这使得查询运行但问题是该字段中还有其他文本我不希望它分组我只想用文本替换名称对于与CASE匹配的项目

当我将文本添加到组中时,我得到此结果。

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

1 个答案:

答案 0 :(得分:2)

问题正是错误所说的。您正在选择不在group by子句中的TransactionsLine.text

您可能希望将案例放在group by子句中:

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
相关问题