2014-12-07 46 views
0

我通過執行以下查詢分組在SQL Server中的數據2008年

select convert(varchar,b.Date,105) as 'Date',m.MenuID, m.MenuName,m.MenuCost, sum(bm.Qty) as 'Qty' , 
    (m.MenuCost*(sum(bm.Qty))) as 'Total' 


    from BillMaster b 
    left join BillMenuMapping bm on bm.MapBillId = b.BillId 
    left join MenuMaster m on m.MenuID = bm.MapMenuId 
    where [email protected]_date 
    group by b.Date,bm.Qty,m.MenuCost,m.MenuName,m.MenuID 

我要出去把要得到以下輸出

Date  | MenuID| MenuName|  MenuCost |  Qty  |   Total 
07-12-2014 | 2  | Special Tea|  20.00  |  2.00  |  40.0000 
07-12-2014 | 2  | Special Tea|  20.00  |  3.00  |  60.0000 
07-12-2014 | 6  | Cold Coffee | 40.00  |  2.00 |  80.0000 

Date  | MenuID| MenuName|  MenuCost |  Qty  |   Total 
07-12-2014 | 2  | Special Tea|  20.00  |  5.00 |   100.0000 
07-12-2014 | 6  | Cold Coffee | 40.00  |  2.00 |   80.0000 

在哪裏我錯了嗎?請幫忙。

以下是我的表結構

Bill Master 

BillId varchar(30) 
TableNo int Checked 
Date datetime  
id int 


BillMenuMapping 


MapID int 
MapMenuId int 
MapBillId varchar(30) 
Qty decimal(7, 2) 


MenuMaster 


MenuID int 
MenuName varchar(100)  
MenuCost decimal(7, 2) 
ManuActive bit 

是不是因爲我有不同的賬單號這就是爲什麼越來越重複的記錄?

回答

1

您需要從Group by刪除bm.Qty。嘗試改變你的查詢是這樣的。

SELECT CONVERT(VARCHAR, b.date, 105) AS 'Date', 
     m.menuid, 
     m.menuname, 
     m.menucost, 
     Sum(bm.qty)      AS 'Qty', 
     m.menucost * (Sum(bm.qty)) AS 'Total' 
FROM billmaster b 
     LEFT JOIN billmenumapping bm 
       ON bm.mapbillid = b.billid 
     LEFT JOIN menumaster m 
       ON m.menuid = bm.mapmenuid 
WHERE b.date = @from_date 
GROUP BY b.date, 
      m.menucost, 
      m.menuname, 
      m.menuid