如何在 SELECT 部分中包含 BIT 类型列而不将其包含在 T-SQL 中的 GROUP BY 中?
这是我的 T-SQL 查询,
SELECT
ProductID,
VendorID,
ProductName= MAX(ProductName),
VendorName = MAX(VendorName),
IsActive = MAX(IsActive) # This brings error
FROM ProductVendorAssoc
GROUP BY
ProductID,
VendorID
我只想对 ProductID 和 VendorID
字段应用 GROUP BY
,但需要填充 ProductID、VendorID、ProductName、VendorName , IsActive
字段。
在这里,我使用聚合函数 MAX(ProductName)
来避免分组依据列表中的 ProductName
。
但同样的技巧不适用于 BIT 列,因为操作数数据类型 bit 对于 max 运算符无效。
如何在 SELEC
T 部分中包含 BIT
类型列而不将其包含在 GROUP BY
中?
更新。
如果我需要在SELECT
中包含INT
列(例如UserID
),我应该做什么同样的方式
Here is my T-SQL query
SELECT
ProductID,
VendorID,
ProductName= MAX(ProductName),
VendorName = MAX(VendorName),
IsActive = MAX(IsActive) # This brings error
FROM ProductVendorAssoc
GROUP BY
ProductID,
VendorID
I want to apply GROUP BY
only for the ProductID and VendorID
fields, but need to populate the ProductID, VendorID, ProductName, VendorName, IsActive
fields.
Here I used the agreggate function MAX(ProductName)
to avoid ProductName
in the group by list.
But the same trick is not working for BIT
columns as operand data type bit is invalid for max operator.
How can i include BIT
type column in SELEC
T part with out including it on the GROUP BY
?
Update.
What should I need to do if i need to include an INT
column like UserID
in SELECT
in the same way
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 SQL2005/2008 中,这将如下所示:
In SQL2005/2008 this would be look like this:
将 CASE 表达式放在那里,或者将其转换为 int:
或者,
显然,您还应该意识到,这意味着结果集中的 ProductName、VendorName 和 IsActive 列中的值可能全部来自基中的不同行桌子。
如果您希望这三列实际上全部来自同一行(假设 SQL Server 2005 或更高版本),您可以执行以下操作:
Put a CASE expression in there, or convert it to int:
or,
You should also be aware, obviously, that this means that the values in the ProductName, VendorName and IsActive columns in the result set may all come from different rows in the base table.
If you want those three columns to actually all be from the same row (and assuming SQL Server 2005 or later), you'd do something like:
更短的方法来做到这一点:
Shorter way to do this: