简体   繁体   English

用于连接SUM和order by子句的两个表的数据的SQL查询

[英]Sql query for joining data of two table with SUM and order by clause

I have two tables in my database. 我的数据库中有两个表。 tbl_Transaction_Detail and tbl_Categrory_Type . tbl_Transaction_Detailtbl_Categrory_Type tbl_Transaction_Detail uses Category_Type_ID of tbl_Category_Type as foreign key. tbl_Transaction_Detail使用Category_Type_IDtbl_Category_Type为外键。 here is my tables: 这是我的桌子:

tbl_Category_Type

tbl_Transaction_Detail

i want to SUM the Quantity of tbl_Transaction_Detail for the Category_Type_ID (say 31) . 我想为Category_Type_ID (比如31)提供tbl_Transaction_DetailQuantity

here is my query for this (in sql server 2008) 这是我对此的查询(在sql server 2008中)

SELECT CAT.Category_type_Name,
CAT.Description,
CAT.Image_url,
CAT.Price,
CAT.Weight,
Sum(TD.Quantity)'Quantity' from tbl_Transaction_Detail as TD 
inner join tbl_Category_type as CAT 
on TD .Category_Type_ID= CAT.Category_type_ID 
WHERE TD.Category_Type_ID = 31
ORDER BY CAT.Category_type_Name,
CAT.Description,
CAT.Image_url,
CAT.Price,
CAT.Weight

but it shows error for all column selection one by one. 但它逐一显示所有列选择的错误。

You have to use group by clause, Include each column in group by clause which you want to select except the column for which you are using aggregate function. 您必须使用group by子句,包括要在其中选择的group by子句中的每个列,但要使用聚合函数的列除外。 Kindly use table aliases for better readability. 请使用表别名以提高可读性。

  SELECT CAT.Category_type_Name
  ,CAT.Description
  ,CAT.Image_url
  ,CAT.Price
  ,CAT.Weight
  ,Sum(TD.Quantity) as Quantity
  FROM tbl_Transaction_Detail TD
  INNER JOIN tbl_Category_type CAT
  on TD.Category_Type_ID=CAT.Category_type_ID 
  WHERE TD.Category_Type_ID=31 
  GROUP BY CAT.Category_type_Name
  ,CAT.Description
  ,CAT.Image_url
  ,CAT.Price
  ,CAT.Weight
  ORDER BY CAT.Category_type_Name
  ,CAT.Description
  ,CAT.Image_url
  ,CAT.Price
  ,CAT.Weight

Just missing a group by for SQL server.... and use table aliases for readability and spacing! 只是为SQL服务器错过了一个组....并使用表别名来提高可读性和间距!

select CT.Category_type_Name
      ,CT.Description
      ,CT.Image_url
      ,CT.Price
      ,CT.Weight
      ,Sum(TD.Quantity) as Quantity
FROM tbl_Transaction_Detail TD
INNER JOIN tbl_Category_type CT
  on TD.Category_Type_ID=CT.Category_type_ID 
WHERE TD.Category_Type_ID=31 
GROUP BY CT.Category_type_Name
        ,CT.Description
        ,CT.Image_url
        ,CT.Price
        ,CT.Weight
ORDER BY CT.Category_type_Name
        ,CT.Description
        ,CT.Image_url
        ,CT.Price
        ,CT.Weight

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM