2016-05-13 56 views
2

我有一個MSSQL數據庫和下面的表Mssql中查詢問題

WHE

+----------+----------+----------+ 
| Item No_ | Bin Code | Quantity | 
+----------+----------+----------+ 
| 0000955 | K2-3-3 | -2  | 
+----------+----------+----------+ 
| 0000955 | C2-2-4 | 3  | 
+----------+----------+----------+ 
| 0000955 | K2-3-3 | 5  | 
+----------+----------+----------+ 
| 0000955 | K2-3-3 | 1  | 
+----------+----------+----------+ 
| 0000955 | C2-2-4 | -1  | 
+----------+----------+----------+ 
| 0000955 | K2-3-3 | -10  | 
+----------+----------+----------+ 
| 0000955 | C2-2-4 | 7  | 
+----------+----------+----------+ 
| 0000955 | K2-3-3 | 3  | 
+----------+----------+----------+ 
| 0000955 | C2-2-4 | 8  | 
+----------+----------+----------+ 

項目

當我執行查詢

select [Bin Code], 
sum([Quantity]) 
from dbo.[whe] 
where [Item No_]='0000955'GROUP BY [Bin Code] 

獲取返回的結果

+----------+----------+ 
| Bin Code | Quantity | 
+----------+----------+ 
| K2-3-3 | -3  | 
+----------+----------+ 
| C2-2-4 | 17  | 
+----------+----------+ 

但我需要這樣的工作

select we.[Bin Code], 
sum(we.[Quantity]), 
it.[Item No_], 
it.[Desc], 
from dbo.[whe] as we, 
dbo.[item] as it 
and it.[No_]=we.[Item No_] 

我想是這樣的結果

+-----------------+--------+----------+----------+ 
| Item No_ | Desc | Bin Code | Quantity | 
+-----------------+--------+----------+----------+ 
| 0000955   | Valve | K2-3-3 | -3  | 
+-----------------+--------+----------+----------+ 
| 0000955   | Valve | C2-2-4 | 17  | 
+-----------------+--------+----------+----------+ 

但查詢不是可執行文件,並得到像

錯誤

列'dbo.Item.No_'在選擇列表中無效beca使用它不包含在聚合函數或GROUP BY子句中。

+2

您是否可以使用預期的輸出? – Dhaval

+0

如果要在使用GROUP BY時選擇列,則它們或者需要是GROUP BY子句的一部分或集合函數(例如:SUM)。或者你需要重新思考你的方法,也可以考慮SUM的窗口函數版本。 –

+0

您的預期結果請。並且你的查詢有2個錯誤:**,**之前的**; '舊式連接';最後'和'必須改成'開'(如果你保留舊的風格加入,然後'在哪裏);壞聚合總和。未完待續.... –

回答

0

如果你想顯示desc列,你可以使用下面的查詢。

select t1.[Bin Code],t1.[Quantity],t1.[Item No_],t2.[Desc] (select [Bin Code], 
sum([Quantity]) as [Quantity],[Item No_] 
from dbo.[whe] 
where [Item No_]='0000955'GROUP BY [Bin Code],[Item No_]) t1 
left join dbo.[Item] t2 
on (t1.[Item No_]=t2.[Item No_]) 
1

如果你想加入到輸出Item No_Desc,你必須包括他們在group by的錯誤陳述。

select [Item No_], [Desc], [Bin Code], sum([Quantity]) 
from dbo.[whe] w 
inner join dbo.[Item] i 
on w.[Item No_] = i.[Item No_] 
group by [Item No_], [Desc], [Bin Code]