我想从表中选择日期列值,但不想按日期分组。 是否可以。 因为我想使用其他列对数据进行分组。
SELECT DISTINCT gin.GoodsIssueNoteNumber,gini.GoodsIssueNoteItemNumber,
sp.OrgPath,ISNULL(gini.IssuedQuantity,0) as 'Quantity',
gin.MRN, sp.SpareName,sp.SysId as 'spareid',
stc.StoreName,sp.ItemGroupName,sp.PartCode,
SUM(stc.StockCount) as stockCount,
SUM(stc.TotalInventoryValue) as StockValue,
ISNULL(gini.Cost,0) as WeightedAverageItemCost,
ROUND (gini.IssuedQuantity * gini.Cost,2) as 'TotalIssued Cost',
gin.Date as 'GIDATE'
FROM vwSpare sp
INNER JOIN vwGoodsIssueNoteItem gini
on sp.SysId=gini.Spare
INNER JOIN vwGoodsIssueNote gin
on gin.SysId in (SELECT AssociatingId FROM GoodsIssueNoteAssociation
WHERE AssociatedId=gini.SysId and IsActive=1)
LEFT JOIN vwStock stc
on stc.Spare=sp.SysId and stc.GoodsIssueNoteId is not null
and gin.StoreIDName=stc.StoreName
WHERE IsRepairable=0 and Scrap=0 and Repaired=0 and sp.IsActive=1
and gin.IsActive=1 and gin.Date > DATEADD(mm,-6,GETDATE()) and gini.IsActive=1
GROUP BY sp.SpareName,stc.StoreName,sp.OrgPath,gini.IssuedQuantity,gin.MRN,
sp.SysId,sp.ItemGroupName,sp.PartCode,gini.Cost,
gin.GoodsIssueNoteNumber,gini.GoodsIssueNoteItemNumber,gin.Date
我不需要 gin.Date in group by
最佳答案
SQL 要求所有非聚合字段都位于 GROUP BY 子句中。但是,您可以这样做:
SELECT b.ungroupedColumn, -- your ungrouped columns
a.* -- your grouped columns
FROM (SELECT Column1, Column2, sum(Column3)
FROM mytable
GROUP BY Column1, Column2) a
INNER JOIN mytable b ON a.Column1 = b.Column1
我们的想法是,您带回分组数据,减去额外的列,然后将这些结果连接回表中以添加未分组的列。
这是一个示例,假设我有以下产品库存:
Type Name Qty
---------- ---------- -----------
Fruit Apple 1
Fruit Orange 2
Fruit Banana 3
Vegetable Carrot 4
Vegetable Cucumber 5
Vegetable Peas 6
我可以运行以下查询:
SELECT b.[Name],
a.*
FROM (SELECT [Type], sum ([Qty]) as Qty_Of_Type
FROM Produce
GROUP BY [Type]) a
INNER JOIN Produce b ON a.[Type] = b.[Type]
它将返回以下结果:
Name Type Qty_Of_Type
---------- ---------- -----------
Apple Fruit 6
Orange Fruit 6
Banana Fruit 6
Carrot Vegetable 15
Cucumber Vegetable 15
Peas Vegetable 15
关于sql - 在 Sql Server 查询中忽略分组依据中的日期列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20867674/