我有一张像
这样的表| Name | Address | (Column Name)
| rakesh | ashok nagar |
| mahesh | ashok nagar |
| rajesh | ashok nagar |
| rakesh1 | ashok nagar |
| rakesh2 | ashok nagar |
| rakesh4 | mayur vihar |
| rakesh5 | laxmi nahar |
| rakesh6 | laxmi nahar |
| rakesh7 | laxmi nahar1 |
| rakesh8 | laxmi nahar1 |
我需要这样的数据
+-------------+--------------+---------+
| count(name) | Address | Name |
+-------------+--------------+---------+
| 5 | ashok nahgar | rakesh,mahesh,rajesh,rakesh1,rakesh2|
| 2 | laxmi nahar | rakesh5,rakesh5|
| 2 | laxmi nahar1 | rakesh7,rakesh8 |
| 1 | mayur vihar | rakesh4 |
+-------------+--------------+---------+
我可以使用临时表获得相同但我需要使用单行查询来获得相同的结果。
有可能吗?
答案 0 :(得分:1)
You have tagged oracle. So we have Listagg function in oracle helps you to do this.
select count(name),address,listagg(name,',') within group(order by name) "name"
from table
group by address;
答案 1 :(得分:0)
试试这个(当你标记sql server时),
SELECT Address,
Stuff((SELECT ', ' + Cast(NAME AS VARCHAR(10)) [text()]
FROM #Your_Table
WHERE Address = t.Address
FOR XML PATH(''), TYPE) .value('.', 'NVARCHAR(MAX)'), 1, 2, ' ') List_Output,
Count(Address) As [Count]
FROM #Your_Table t
GROUP BY Address