[英]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. 我正在使用SQL Server,并且遇到以下问题,我希望有人可以帮助我。
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 我不想在GROUP BY子句中包含文本,是的,这会使查询运行,但是问题是字段中还有其他文本,我不希望将其分组,我只想将Name替换为Text以匹配项目案子
when i add Text to the group by i get this result. 当我将文本添加到组时,我得到了这个结果。
43036 SPECIAL 73.0000
43036 SPECIAL 6.0000
Issue is exactly what the error says. 问题恰恰是错误所说的。 You are selecting
TransactionsLine.text
which is not in the group by clause. 您正在选择不在group by子句中的
TransactionsLine.text
。
you probably want to put the case in your group by
clause: 您可能希望将案例放在您的
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.