1

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
------------------------------------
4

2 回答 2

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 必须是唯一的

于 2013-09-21T16:07:12.200 回答
0

不幸的是,不可能通过查询获得第一个输出,因为需要为每个不同的城市生成列。

这是在 ms-access 中获得第二个变体的方法,但它不是最优的:define sfunction

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]
于 2013-09-21T15:44:18.700 回答