日期:2014-05-16  浏览次数:20503 次

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

表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表以后可能数据不少,执行效率最高的方式得到上面的结果,有建议的吗?

------解决方案--------------------
执行效率最高是用视图索引(Indexed View).

或单独建表存统计结果,并在表A上建触发器,当有新增修改删除表A的数据时,同步更新统计表的数据.
------解决方案--------------------
这样吗:

--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,          &n