Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/73.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 输出计数为值_Sql_Sql Server - Fatal编程技术网

Sql 输出计数为值

Sql 输出计数为值,sql,sql-server,Sql,Sql Server,我是SQL新手,希望实现以下目标 输入: ------------------------- 姓名|姓氏|年龄 ------------------------- 姓名1 |姓氏1 |年龄1A 姓名1 |姓氏1 |年龄1b 姓名2 |姓氏2 |年龄2a 姓名2 |姓氏2 |年龄2B 输出: ------------------------------- 姓名|姓|可能 ------------------------------- 姓名1 |姓氏1 |年龄1A、1B 姓名2 |姓2 |年龄2a

我是SQL新手,希望实现以下目标

输入:

-------------------------
姓名|姓氏|年龄
-------------------------
姓名1 |姓氏1 |年龄1A
姓名1 |姓氏1 |年龄1b
姓名2 |姓氏2 |年龄2a
姓名2 |姓氏2 |年龄2B
输出:

-------------------------------
姓名|姓|可能
-------------------------------
姓名1 |姓氏1 |年龄1A、1B
姓名2 |姓2 |年龄2a、2b
我想肯定应该按姓名分组,但我不知道如何创建“可能”列。

您可以使用:

对于旧版本,您可以使用xml方法:

select name, surname,
       stuff(( select concat(', ', t1.PossibleAges)
               from table t1
               where t1.name = t.name and t1.surname = t.surname
               for xml path('')
             ), 1, 1, ''
            ) as PossibleAges
from (select distinct name, surname from table t) t;

离题,但将年龄存储到数据库通常不是最好的主意——它们往往会随着时间的推移而变化;当然,您可以在某些事件(结婚、死亡)中存储年龄,以使查询或分析变得更简单/更快。有“没有”名字的“马”,谢谢,我已经添加了DBMS。@Arvo,这只是一个示例!我的真实输入包含与工作相关的信息,我不必在网上分享;)谢谢你的回答。嗨,非常感谢你的回答!不幸的是,我收到以下错误消息:“STRING_AGG”不是可识别的内置函数名。你知道有什么解决办法吗?@ijswift。您可以在
xml
方法中使用较旧的样式。我收到第4行的错误消息,说无法绑定多部分标识符。。。
select name, surname,
       stuff(( select concat(', ', t1.PossibleAges)
               from table t1
               where t1.name = t.name and t1.surname = t.surname
               for xml path('')
             ), 1, 1, ''
            ) as PossibleAges
from (select distinct name, surname from table t) t;