在sql中使用与SUM()的连接不执行任何操作

时间:2016-05-23 07:43:48

标签: mysql sql-server

我想在库存中显示所选商品时,在添加到购物车区域中显示产品(仅限)。我使用了SUM(数量)并加入了两个表,如下所示:

 da.SelectCommand = new SqlCommand("SELECT ct.Weight,ct.Image_url,td.Category_Unit,ct.Description,ct.Category_type_ID,td.Category_Type_ID,td.Transaction_Detail_ID, ct.Category_type_ID,ct.Category_type_Name,td.Price,sum(td.Quantity) as Quantity from tbl_Category_type as ct inner join tbl_Transaction_Detail as td on ct.Category_type_ID=td.Category_type_ID where ct.Category_type_ID='" + val + "' AND td.Status='Purchase' group by ct.Category_type_ID,td.Category_Type_ID,td.Transaction_Detail_ID, ct.Category_type_ID,ct.Category_type_Name,td.Price,td.Category_Unit,ct.Description,ct.Image_url,ct.Weight", conn);

由于从两个表中选择了很多列,我只代表一个列进行聚合。我也尝试过:

 da.SelectCommand = new SqlCommand("SELECT ct.*,td.*,ct.Category_type_Name,td.Price,sum(td.Quantity) as Quantity from tbl_Category_type as ct inner join tbl_Transaction_Detail as td on ct.Category_type_ID=td.Category_type_ID where ct.Category_type_ID='" + val + "' AND td.Status='Purchase' group by ct.Category_type_Name,td.Price", conn);

但后面显示错误:

  

tbl_Category_Detail.Category_type_ID未在聚合区域初始化。

这是同一产品在前端重复的方式。但是我希望它只显示一次(因为我在tbl_Category_Detail中有两个关于Neckless0001的条目)

enter image description here

1 个答案:

答案 0 :(得分:0)

我认为你所寻找的是HAVING条款。

SELECT
...
HAVING sum(td.Quantity) > 1

或通过内部查询的简洁方式

SELECT * FROM (
...
) Q
WHERE Quantity > 1