我有两张桌子
InvoiceHead(InvoiceID,RetailerID,ExecutiveID,InvoiceDate)
InvoiceItem(InvoiceID,项ID,数量,合同,金额)。
我希望按ExecutiveId和ItemId分组销售数量。
我尝试了以下查询,但它没有给出预期的结果。两个列的分组都没有发生。如下面的屏幕截图所示,相同的执行和项目没有加在一起。它们分为两行
结果的屏幕截图
SELECT
SecItem.ItemID
,SecHead.ExecutiveID
,sum(SecItem.QTY) AS Total_Qty
FROM Secondary_Sales.dbo.InvoiceHead AS SecHead
INNER JOIN Secondary_Sales.dbo.InvoiceItem AS SecItem
ON SecHead.InvoiceID = SecItem.Invoice_ID
GROUP BY
SecItem.ItemID
,SecHead.ExecutiveID
此查询在mysql中工作并提供预期结果,但同样的查询在msqlserver
中不起作用答案 0 :(得分:0)
尝试使用以下查询..
;with cte_1
as
(SELECT InvoiceID,ItemID,SUM(QTY) OVER (partition by ItemID order by ItemID)New_QTY
FROM InvoiceItem )
SELECT c.ItemID,h.ExecutiveID,sum(c.New_QTY) AS Total_Qty
FROM Secondary_Sales.dbo.InvoiceHead h
JOIN cte_1 c
on h.InvoiceID=c.InvoiceID
GROUP BY h.ExecutiveID,c.ItemID
如果您想根据executiveId和item id提取总和,请使用以下查询。
;with cte_1
as
(SELECT c.ItemID,h.ExecutiveID
,ROW_NUMBER() OVER(partition by h.ExecutiveID,c.ItemID order by h.ExecutiveID,c.ItemID) RNO
,SUM(QTY) OVER (partition by h.ExecutiveID,c.ItemID order by h.ExecutiveID,c.ItemID) AS Total_Qty
FROM Secondary_Sales.dbo.InvoiceHead h
JOIN econdary_Sales.dbo.InvoiceItem c
on h.InvoiceID=c.InvoiceID)
SELECT ExecutiveID,ItemID,Total_Qty
FROM cte_1
WHERE RNO=1
答案 1 :(得分:0)
给定的查询应该有效,SQL Server不会像MySql那样实现这样的事情。我怀疑这是一个数据问题。我怀疑某些ID的数据有尾随空格。 " GALSR02"不等于" GALSR02"。尝试此查询以查看是否是这种情况:
SELECT
RTRIM(SecItem.ItemID)
,RTRIM(SecHead.ExecutiveID)
,sum(SecItem.QTY) AS Total_Qty
FROM Secondary_Sales.dbo.InvoiceHead AS SecHead
INNER JOIN Secondary_Sales.dbo.InvoiceItem AS SecItem
ON RTRIM(SecHead.InvoiceID) = RTRIM(SecItem.Invoice_ID)
GROUP BY
RTRIM(SecItem.ItemID)
,RTRIM(SecHead.ExecutiveID)
如果可以,那么你需要运行它来纠正数据,并首先研究空白区域是如何到达那里的。一旦数据得到纠正,您就可以恢复原始查询。
UPDATE Secondary_Sales.dbo.InvoiceHead
SET ExecutiveID = RTRIM(ExecutiveID), InvoiceID = RTRIM(InvoiceID)
UPDATE Secondary_Sales.dbo.InvoiceItem
SET ItemID = RTRIM(ItemID), Invoice_ID = RTRIM(Invoice_ID)
答案 2 :(得分:-1)
尝试使用以下查询希望它有所帮助。
SELECT SecItem.ItemID,SecHead.ExecutiveID,sum(SecItem.QTY) AS Total_Qty
FROM Secondary_Sales.dbo.InvoiceHead AS SecHead
INNER JOIN Secondary_Sales.dbo.InvoiceItem AS SecItem ON SecHead.InvoiceID = SecItem.Invoice_ID
GROUP BY SecItem.ItemID,SecHead.ExecutiveID,SecItem.QTY