这是我的T查询
SELECT
ProductID,
VendorID,
ProductName= MAX(ProductName),
VendorName = MAX(VendorName),
IsActive = MAX(IsActive) # This brings error
FROM ProductVendorAssoc
GROUP BY
ProductID,
VendorID我只想将GROUP BY应用于ProductID and VendorID字段,但需要填充ProductID, VendorID, ProductName, VendorName, IsActive字段。
在这里,我使用了agreggate函数MAX(ProductName),以避免ProductName中的组按列表。
但同样的技巧不适用于BIT列,因为操作数数据类型位对于max运算符无效。
如何将BIT类型列包含在SELECT部件中,而不将其包含在GROUP BY上
更新.
如果我需要以同样的方式在INT列中包括一个像UserID这样的SELECT列,我需要做什么?
发布于 2011-05-19 04:43:39
将CASE表达式放入其中,或将其转换为int:
IsActive = MAX(CASE WHEN IsActive=1 THEN 1 ELSE 0 END)或,
IsActive = MAX(CONVERT(int,IsActive))显然,您还应该知道,这意味着结果集中的ProductName、VendorName和IsActive列中的值都可能来自基表中的不同行。
如果希望这三列实际上都来自同一行(并假设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发布于 2015-11-12 21:17:08
做这件事的更短的方法:
IsActive = MAX(0+IsActive)发布于 2011-05-19 04:50:10
在like 2005/2008中,如下所示:
select ProductId, VendorId, ProductName, VendorName, IsActive
from
(
select *, row_number() over (partition by ProductId, VendorId order by ProductId) RowNumber
from Production.Product
) tt
where RowNumber = 1https://stackoverflow.com/questions/6053840
复制相似问题