简体   繁体   中英

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_Detail uses Category_Type_ID of tbl_Category_Type as foreign key. 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) .

here is my query for this (in 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. 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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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