簡體   English   中英

有關GROUP BY SQL Server的聚合函數的問題

[英]Question about aggregate functions with GROUP BY SQL Server

我有例如表中不同類型的10-15個字段(varchar,nvarchar,int,float,datetime等),我需要制作GROUP BY,所以。 我必須在所有這些領域使用聚合的什么功能? MAX還是其他什么? 這非常重要嗎?

SELECT
    intFacilityRTOPID,
    MAX(ObjectSystem_r_Equipment) ObjectSystem_r_Equipment,
    MAX(ObjectBuilding_r_Equipment) ObjectBuilding_r_Equipment,
    MAX(intenum_EquipmentTypeID) intenum_EquipmentTypeID,
    MAX(correctionDate) correctionDate
FROM [RTOPv4History].[dbo].[FacilityRTOP]
WHERE cast(correctionDate as bigint) <= @correctionDate
GROUP BY intFacilityRTOPID

聽起來你可能不明白Group By作用。 Group By建立一組“bin”或“buckets”,由group by列或表達式的值定義,用於控制查詢的輸出。 即,查詢的結果行將被約束為由列和/或表達式按組定義的值的唯一組合,並且每行中的所有數據都受到原始表的“定義”的子集的約束。 。

eoutput中與列/表組之一不完全相同的任何列必須使用眾多聚合函數之一來指定和/或計算為該列生成的值。 生成的值將僅從原始表中與group By列/表達式匹配的那些行中的實際表列值中獲取。 因此,如果您使用MAX() ,您將獲得該值的最大子集,如果您使用AVG()您將獲得平均值等等...

如果你真的不想做任何聚合,那么考慮只使用Distinct關鍵字....

 SELECT Distinct intFacilityRTOPID, 
     ObjectSystem_r_Equipment ObjectSystem_r_Equipment,
     ObjectBuilding_r_Equipment ObjectBuilding_r_Equipment, 
     intenum_EquipmentTypeID intenum_EquipmentTypeID,
     correctionDate correctionDate 
 FROM [RTOPv4History].[dbo].[FacilityRTOP] 
 WHERE cast(correctionDate as bigint) <= @correctionDate 

如果互補列全部相等,您可能想要

SELECT * FROM (
  SELECT DISTINCT(intFacilityRTOPID) 
  FROM [RTOPv4History].[dbo].[FacilityRTOP]
  WHERE cast(correctionDate as bigint) <= @correctionDate
) a CROSS JOIN (
  SELECT TOP(1) 
    ObjectSystem_r_Equipment,
    ObjectBuilding_r_Equipment,
    intenum_EquipmentTypeID,
    correctionDate
  FROM [RTOPv4History].[dbo].[FacilityRTOP]
  WHERE cast(correctionDate as bigint) <= @correctionDate
) b

根據表的大小,它可以表現更好。 警告:我沒有嘗試,如果這工作,我寫的記憶:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM