客户表 A
ID 名字 金额消费记录表 BID 客户表ID  现金支付(元) 刷卡(元)消费日期消费明细表 CID 消费表ID 产品ID 消费数量
-------------------------------------------------------------
条件: 时间段,消费金额>=、<=,消费次数>=、<=于,平均消费额>=、<=,消费数量>=、<=  等查询结果客户名  消费金额  平均消费金额  消费次数  消费数量等待各位大虾给出效率高的SQL查询,谢谢~!

解决方案 »

  1.   

    消费记录表 B表里面有A表的id,至于查询,级联查询即可以。性能可以从多方面去考虑,索引、表字段的多少,服务器和你程序实现都有可能影响。
      

  2.   

    多表联查先做个视再查,要不写sql烦死了。查询上没什么性能之类的,先用有索引的字段做过滤会快一点。
      

  3.   

    create table tbA(ID int,uname nvarchar(20))
    insert into tbA select 1,'aaa' union all select 2,'bbb'
    create table tbB(id int,userid int,oof decimal(18,2),[card] decimal(18,2),dt datetime)
    insert into tbB select 1,1,328.1,328.1,0
    insert into tbB select 2,1,372.2,372.2,0
    insert into tbB select 3,2,837.0,0,837.0
    create table tbC(id int,consid int,pid int,connumber int)
    insert into tbC select 1,1,100,12
    insert into tbC select 2,1,101,15
    insert into tbC select 3,1,132,8
    insert into tbC select 4,2,154,19
    insert into tbC select 5,2,166,10
    insert into tbC select 6,3,104,22
    go
    select t1.uname as 客户名称,t1.o as 消费金额,t1.v as 平均消费金额,t1.c as 消费次数,t2.s as 消费数量
    from(
    select a.id,a.uname,sum(b.oof) as o,count(*) as c,sum(b.oof)/count(*) as v
    from tbA a inner join tbB b on b.userid=a.id
    group by a.id,a.uname
    )t1 inner join (
    select a.id,sum(c.connumber)as s from tbA a inner join tbB b on a.id=b.userid inner join tbC c on b.id=c.consid
    group by a.id
    )t2 on t1.id=t2.id
    go
    drop table tbA,tbB,tbC
    /*
    客户名称              消费金额                               平均消费金额                            消费次数     消费数量
    -------------------- --------------------------------------- --------------------------------------- ----------- -----------
    aaa                  700.30                                  350.150000                              2           64
    bbb                  837.00                                  837.000000                              1           22(2 行受影响)*/
      

  4.   

        客户名     消费金额   sum()
     
         平均消费金额  avg()
     
         消费次数 消费数量  (case when then end)