日期:2014-05-17  浏览次数:20872 次

超难!这样的分组能实现吗?
select   count(*),sum(yjje)   from   app_jhpz   where   gs_jbrq   like   '2007-01% '   group   by   j_dwmc;

现在数据库中的j_dwmc字段有两类的值,一类为测井,一类为钻井,所以,查询出来的是两行数据:
    COUNT(*)     SUM(YJJE)
----------   ----------
                  2                   64
                  1                   20

但是这两行数据没有顺序,也就是说,我不知道哪行是测井的哪行是钻井的,而且,数据库中的j_dwmc字段只能有8种固定的值,我要求:按我规定的j_dwmc值的顺序来排列分组后的结果,如果j_dwmc中只有5种值,那么,其它的三种也要按顺序排列出来,只不过要用0来填充。
如何实现?谢谢大家!


------解决方案--------------------
try

Select
A.j_dwmc,
IsNull(B.countj_dwmc, 0) As countj_dwmc,
IsNull(B.sumyjje, 0) As sumyjje
From
A
Left Join
(select j_dwmc, count(*) As countj_dwmc, sum(yjje) As sumyjje from app_jhpz where gs_jbrq like '2007-01% ' group by j_dwmc) B
On A.j_dwmc = B.j_dwmc
------解决方案--------------------
select isnull(b.行数,0),isnull(b.总数,0) from
(select 1 orderno, '第一种值 ' Name union select 2, '第一种值 ' union select 3, '第一种值 ')a left join
(select j_dwmc,count(*)行数,sum(yjje)总数 from app_jhpz where gs_jbrq like '2007-01% ' group by j_dwmc)b
on b.j_dwmc=a.Name order by a.orderno

------解决方案--------------------

create table app_jhpz(yjje int,j_dwmc varchar(10),gs_jbrq varchar(10)) drop table app_jhpz
insert app_jhpz select 100, '第一种值 ', '2007-01-02 '
insert app_jhpz select 200, '第一种值 ', '2007-01-03 '
insert app_jhpz select 300, '第二种值 ', '2007-01-04 '
insert app_jhpz select 400, '第三种值 ', '2007-01-05 '
insert app_jhpz select 500, '第二种值 ', '2007-01-06 '
insert app_jhpz select 600, '第三种值 ', '2007-01-07 '
insert app_jhpz select 700, '第一种值 ', '2007-01-08 '
insert app_jhpz select 800, '第二种值 ', '2007-01-08 '
insert app_jhpz select 900, '第三种值 ', '2007-02-02 '
insert app_jhpz select 1000, '第一种值 ', '2007-02-02 '
----------------------------
select isnull(b.行数,0),isnull(b.总数,0) from
(select 1 orderno, '第一种值 ' Name union select 2, '第二种值 ' union select 3, '第三种值 ')a left join
(select j_dwmc,count(*)行数,sum(yjje)总数 from app_jhpz where gs_jbrq like '2007-01% ' group by j_dwmc)b
on b.j_dwmc=a.Name order by a.orderno
-----------------------
3 1000
3 1600
2 1000