~~~~~~~~~这句SQL怎写效率最高?~~~~~~~~~~

hxm20003 2014-02-26 01:59:35

表A
id name(名称) cat1(大类) cat2(中类) cat3(小类)
1 A01 1 10 101
2 A02 1 10 101
3 A03 1 11 111
4 A04 1 10 101
5 A05 2 20
6 A06 2 21
...

结果
Cat(大/中/小类) CountQty
1 4
10 3
11 1
101 3
111 1
2 2
20 1
21 1

A表以后可能数据不少,执行效率最高的方式得到上面的结果,有建议的吗?
...全文
68 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
KeepSayingNo 2014-02-26
  • 打赏
  • 举报
回复
你唯一要做的就是把C替换成你的表名,得到的结果如下:


3楼需要遍历原始表3次,如果表的数据比较多,效率上可能比较慢
KeepSayingNo 2014-02-26
  • 打赏
  • 举报
回复

select catvalue as [Cat(大/中/小类)],COUNT(1) as CountQty from
(
    select * from C
    unpivot
    (catvalue for cattype in(cat1,cat2,cat3)) as upt
) t group by catvalue
LongRui888 2014-02-26
  • 打赏
  • 举报
回复
排序:
--drop table a

create table A(id int,  name varchar(10),cat1 int,   cat2 int  , cat3 int)


insert into A
select 1   ,'A01',            1,             10,             101 union all
select 2   ,'A02',            1,             10,             101 union all
select 3   ,'A03',            1,             11,             111 union all
select 4   ,'A04',            1,             10,             101 union all
select 5   ,'A05',            2,             20,             null union all
select 6   ,'A06',            2,             21,             null
go


select [Cat(大/中/小类)],COUNT(*) CountQty
from
(
	select cat1 [Cat(大/中/小类)] from A
	union all
	select cat2 from A
	union all
	select cat3 from A
)t
where [Cat(大/中/小类)] is not null
group by [Cat(大/中/小类)]
order by cast([Cat(大/中/小类)] as varchar)
/*
Cat(大/中/小类)	CountQty
1	4
10	3
101	3
11	1
111	1
2	2
20	1
21	1
*/
不过,这个速度,应该快不了
LongRui888 2014-02-26
  • 打赏
  • 举报
回复
这样吗:

--drop table a

create table A(id int,  name varchar(10),cat1 int,   cat2 int  , cat3 int)


insert into A
select 1   ,'A01',            1,             10,             101 union all
select 2   ,'A02',            1,             10,             101 union all
select 3   ,'A03',            1,             11,             111 union all
select 4   ,'A04',            1,             10,             101 union all
select 5   ,'A05',            2,             20,             null union all
select 6   ,'A06',            2,             21,             null
go


select [Cat(大/中/小类)],COUNT(*) CountQty
from
(
	select cat1 [Cat(大/中/小类)] from A
	union all
	select cat2 from A
	union all
	select cat3 from A
)t
where [Cat(大/中/小类)] is not null
group by [Cat(大/中/小类)]
/*
Cat(大/中/小类)	CountQty
1	4
2	2
10	3
11	1
20	1
21	1
101	3
111	1
*/
唐诗三百首 2014-02-26
  • 打赏
  • 举报
回复
执行效率最高是用视图索引(Indexed View). 或单独建表存统计结果,并在表A上建触发器,当有新增修改删除表A的数据时,同步更新统计表的数据.

22,209

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧