MS-access查询:按名称和年龄分组,获取没有重复数据的详细信息(姓名和年龄) 请在下面找到详细信息
表架构:
id: integer
name: varchar(100)
age: integer
city: varchar(100)
表中的记录:
------------------------------------
id| name | age | city
------------------------------------
1 | ram | 25 | bhopal
2 | brajesh | 30 | indore
3 | ram | 25 | indore
4 | ram | 26 | bhopal
5 | ram | 27 | mumbai
6 | brajesh | 30 | mumbai
7 | brajesh | 26 | dehli
------------------------------------
预期结果:
------------------------------------
name | age | city | city
------------------------------------
ram | 25 | bhopal | indore
brajesh | 30 | indore | mumbai
------------------------------------
预期输出的其他格式:
预期结果:
------------------------------------
name | age | city
------------------------------------
ram | 25 | bhopal, indore
brajesh | 30 | indore, mumbai
------------------------------------
答案 0 :(得分:1)
这样可以解决问题:
select distinct d1.name, d1.age, concat(d1.city, ' , ' ,d2.city) AS city from
Details d1 join Details d2
on d1.name = d2.name
and d1.age = d2.age
and d1.city != d2.city
and d1.id < d2.id
以下是SQLFiddle
另请注意,为此, ID必须是唯一的。
答案 1 :(得分:0)
不幸的是,由于需要为每个不同的城市生成列,因此无法通过查询获得第一个输出。
这是如何在ms-access中获取第二个变体,但它不是最佳的: 定义功能
public function SitiesOf(Name as String,Age as long) as String
dim rst as recordset
SitiesOf = ", "
set rst = currentdb.Openrecordset("SELECT [city] FROM [Table] WHERE [name]='" & Name & "' AND [age]=" & Age & ";")
while not rs.eof
SitiesOf = SitiesOf & rst![city] & ", "
rst.MoveNext
wend
rst.close
set rst=Nothing
SitiesOf = left(SitiesOf , len(SitiesOf)-2)
end function
撰写查询
SELECT [name] , [age] , SitiesOf([name],[age]) FROM [Table] GROUP BY [name] , [age]