0

Need to build a SQL Query

I have two tables

tbl_cat
_________________
cat_id | cat_name
tbl_pro
__________________________
pro_id | pro_name | cat_id

now I need data in form of row

e.g

category name | pro name 1 | pro name 2 | pro name 3

OR

Category name | pro name 1 , pro name 2 , pro name 3

my Query is

SELECT ct.cat_name,
       cp.proname
FROM tbl_cat ct
JOIN tbl_pro cp
WHERE ct.cat_id=cp.cat_id;

and it shows result like this

_____________________________
cat Name | Pro Name 
cat Name | Pro Name 1 
cat Name | Pro Name 2 
Gaurav Dave
  • 6,838
  • 9
  • 25
  • 39
Zaheer Ahmad
  • 176
  • 2
  • 11
  • Please visit http://stackoverflow.com/help/how-to-ask and read the guidelines here for how to ask a good question. Also, be sure to add your code so we can see what exactly has been done, and what exactly may need to be fixed or added. Thank you in advance. – EastOfJupiter May 06 '16 at 15:02
  • try to improve my question i think this is better than before – Zaheer Ahmad May 06 '16 at 15:24
  • Get your answer here http://stackoverflow.com/questions/15154644/group-by-to-combine-concat-a-column – Akanksha Singh May 06 '16 at 15:34
  • Unrelated, but: `JOIN tbl_pro cp WHERE ct.cat_id=cp.cat_id;` is invalid SQL. If you use `JOIN` you need to put the join condition in the `ON` clause. `JOIN tbl_pro cp ON ct.cat_id=cp.cat_id;` –  May 09 '16 at 08:22

3 Answers3

0
$result = mysql_query"
SELECT tbl_cat.CatName, tbl_pro.ProName1, tbl_pro.ProName2, tbl_pro.ProName3
FROM tbl_cat
LEFT JOIN tbl_pro
ON tbl_cat.cat_id=tbl_pro.cat_id
";

while($row = mysql_fetch_array($result)) {
 echo "Category: " . $row[CatName] . " Product1: " . $row[ProName1] . " Product2: " . $row[ProName2] . " Product3: " . $row[ProName3];
}
stackunderflow
  • 422
  • 2
  • 5
  • 19
0

If you are using sqlserver2008 R2 or above Try this:

select ct.cat_name,
    STUFF(
             (SELECT DISTINCT ',' + cp.pro_name
              FROM tbl_pro cp INNER JOIN tbl_cat ci on ci.cat_id=cp.cat_id
              where ci.cat_id = ct.cat_id                 
              FOR XML PATH (''))
              , 1, 1, '')  AS ProductList
    FROM tbl_cat ct
    GROUP BY ct.cat_name,ct.cat_id
Sam
  • 2,935
  • 1
  • 19
  • 26
0

You didn't state your DBMS, so this is for Postgres:

SELECT ct.cat_name, string_agg(cp.proname, ',')
FROM tbl_cat ct
  JOIN tbl_pro cp ON ct.cat_id=cp.cat_id
GROUP BY ct.cat_name
ORDER BY ct.cat_name;