如何在SELECT部分​​中包含BIT类型列而不包含在T-SQL中的GROUP BY上?

Mit*_*ran 51 sql t-sql group-by aggregate

这是我的T-SQL查询

SELECT 
    ProductID,
    VendorID,
    ProductName= MAX(ProductName),
    VendorName = MAX(VendorName),
    IsActive = MAX(IsActive) # This brings error 
FROM ProductVendorAssoc 
GROUP BY  
    ProductID,
    VendorID
Run Code Online (Sandbox Code Playgroud)

我想GROUP BY只应用于ProductID and VendorID字段,但需要填充ProductID, VendorID, ProductName, VendorName, IsActive字段.

在这里,我使用agreggate函数MAX(ProductName)来避免ProductName在group by列表中.

但是同样的技巧不适用于BIT列,因为操作数数据类型位对于max运算符是无效的.

如何BITSELECT部分中包含类型列而不包括在GROUP BY

更新.

我应该怎么需要,如果我需要包括做一个INT栏喜欢UserIDSELECT以同样的方式

Dam*_*ver 88

在其中放置一个CASE表达式,或将其转换为int:

IsActive = MAX(CASE WHEN IsActive=1 THEN 1 ELSE 0 END)
Run Code Online (Sandbox Code Playgroud)

要么,

IsActive = MAX(CONVERT(int,IsActive))
Run Code Online (Sandbox Code Playgroud)

您还应该意识到,这意味着结果集中ProductName,VendorName和IsActive列中的值可能都来自基表中的不同行.


如果您希望这三列实际上都来自同一行(并假设SQL Server 2005或更高版本),您可以执行以下操作:

;With Numbered as (
    SELECT *,ROW_NUMBER() OVER (
        PARTITION BY ProductID,VendorID
        ORDER BY /* Something appropriate, or if we just want random... */ newid()) as rn
    FROM ProductVendorAssoc
)
select
    ProductID,
    VendorID,
    ProductName,
    VendorName,
    IsActive
FROM Numbered where rn=1
Run Code Online (Sandbox Code Playgroud)


Mik*_*nov 10

更短的方法:

IsActive = MAX(0+IsActive)
Run Code Online (Sandbox Code Playgroud)