Mssql查询问题

时间:2016-05-13 09:22:34

标签: sql sql-server

我有一个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        |
+----------+----------+----------+

项目

+----------+--------+
| Item No_ | Desc   |
+----------+--------+
| 0000054  | Spring |
+----------+--------+
| 0000087  | Ring   |
+----------+--------+

当我执行查询时

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_'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。

2 个答案:

答案 0 :(得分:1)

如果您希望将<?php include('f1.html'); include('f2.html'); ... ?> Item No_添加到输出中,则必须在Desc中将其包含在错误中。

group by

答案 1 :(得分: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_])