使用WHERE IN查询时出错

时间:2011-05-03 18:01:47

标签: sql sql-server sql-server-2005 select

这是我尝试运行的查询:

Select Status from [transaction] where TransactionID IN (select MAX(CAST(TransactionID AS VARCHAR(36))), sum(debit) 
FROM [transaction]
WHERE  dbo.getday(StartSaleTime) >= '5/1/2011' and dbo.getday(StartSaleTime) <= '5/3/2011'  and Status > -1 And TransactionNo like 'EL%' And TransactionType = 4 
GROUP BY CustomerID, debit HAVING ( COUNT(CustomerID) > 1 ))

它会返回此错误:

Only one expression can be specified in the select list when the subquery is not introduced with EXISTS.

3 个答案:

答案 0 :(得分:3)

您正在选择两件事并尝试将其与IN()一起使用。在尝试执行someId In(ID列表)时,您应该只选择ID。

答案 1 :(得分:3)

它告诉您错误消息中到底出了什么问题。使用in时,您只能在选择列表中指定一列。

如果您将查询更改为此,则应该可以正常工作。

Select Status from [transaction] where TransactionID 

IN (select MAX(CAST(TransactionID AS VARCHAR(36))) as [TransactionID]
FROM [transaction]
WHERE  dbo.getday(StartSaleTime) >= '5/1/2011' and dbo.getday(StartSaleTime) <= '5/3/2011'  and Status > -1 And TransactionNo like 'EL%' And TransactionType = 4 
GROUP BY CustomerID, debit HAVING ( COUNT(CustomerID) > 1 ))

您可以指定多个列,但仅限于使用EXISTS而不是IN

答案 2 :(得分:2)

您的子查询必须只返回一个字段。现在你要返回两个,所以总体查询看起来有点像:

SELECT ... WHERE TransactionID IN ((a,b), (c,d), etc...)

SQL服务器不知道哪个列用于IN的东西,所以它在抱怨。