1个回答
展开全部
sqlserver写法:其他数据库请说明:
创建表,数据:
create table t
(type varchar(1),
data int)
insert into t values ('A',1)
insert into t values ('B',1)
insert into t values ('C',2)
insert into t values ('A',1)
insert into t values ('B',1)
insert into t values ('C',3)
insert into t values ('A',2)
insert into t values ('B',1)
insert into t values ('C',2)
执行:
select a.type,a.data,b.cnt from
(select type, data=stuff((select ','+cast(data as varchar) from (select type,data from t group by type,data) t where type=s.type for xml path('')), 1, 1, '')
from (select type,data from t group by type,data) s
group by type) a,
(select type,COUNT(distinct data) cnt from t group by type) b
where a.type=b.type
结果:
还有,你是不是自己搞的那个结果截图有误?为啥第一行的sum里有2个1,我理解错了?
不重复值的集合和不重复数值个数代表什么?
追问
数据库就是mysql
追答
mysql的话要改下语句:
create table t
(type varchar(1),
data int);
insert into t values ('A',1);
insert into t values ('B',1);
insert into t values ('C',2);
insert into t values ('A',1);
insert into t values ('B',1);
insert into t values ('C',3);
insert into t values ('A',2);
insert into t values ('B',1);
insert into t values ('C',2);
执行:
SELECT
a.type,
b. DATA,
a.cnt
FROM
(
SELECT
type,
count(DISTINCT DATA) cnt
FROM
t
GROUP BY
type
) a,
(
SELECT
s.type,
group_concat(s. DATA) DATA
FROM
(
SELECT
type,
DATA
FROM
t
GROUP BY
type,
DATA
) s
GROUP BY
s.type
) b
WHERE
a.type = b.type
结果:
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询