问题:
mssql中是否可以用group实现如下或者其他解决方案
表t1
id t2id amount otherid
1 1 11 123
2 2 12 234
3 3 13 345
4 4 21 456
5 5 22 567
表t2
id name
1 一
2 一
3 一
4 二
5 二
得到如下结果集:
t2.name t1.amount t1.otherid
一 36 123,234,345
二 43 456,567
解答:
mssql不知道,通过查询mysql文档这么做可以做,已经测试通过。
select t2.name, sum(t1.amount),
GROUP_CONCAT(t1.otherid ORDER BY t1.id ) as otherid
from t1,t2
where t1.t2id=t2.id
group by t2.name
我这里没有mssql的测试环境,mssql应当类似的.但是估计不同的是
GROUP_CONCAT这个函数。
代码
/*@charset utf8*/
/*test in Mysql5.0.24 server*/
DROP DATABASE IF EXISTS `testGroup`;
CREATE DATABASE `testGroup` ;
USE `testGroup`;
/* */
DROP TABLE IF EXISTS `t1`;
CREATE TABLE `t1` (
`id` int,
`t2id` int,
`amount` int,
`otherid` int
) ;
insert into t1 values(1 ,1 ,11 ,123);
insert into t1 values(2 ,2 ,12 ,234);
insert into t1 values(3 ,3 ,13 ,345);
insert into t1 values(4 ,4 ,21 ,456);
insert into t1 values(5 ,5 ,22 ,567);
DROP TABLE IF EXISTS `t2`;
CREATE TABLE `t2` (
`id` int,
`name` varchar(20)
) ;
insert into t2 values(1 ,'一');
insert into t2 values(2 ,'一');
insert into t2 values(3 ,'一');
insert into t2 values(4 ,'二');
insert into t2 values(5 ,'二');
/*
Result:
t2.name t1.amount t1.otherid
一 36 123,234,345
二 43 456,567
*/
select t2.name, sum(t1.amount),
GROUP_CONCAT(t1.otherid ORDER BY t1.id ) as otherid
from t1,t2
where t1.t2id=t2.id
group by t2.name