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

问个关于SQL查询语句,大家帮帮嘛,谢谢了!!
我有个表,表中有如下字段

CREATE TABLE [dbo].[tbName](
[dwdm] [varchar](10) NULL, --单位代码
[dwmc] [varchar](60) NULL, --单位名称
[qk] [numeric](19,2) NULL, --累计欠款金额
[qkts] [int] NULL, --累计欠款天数
[djsj] [datetime] NOT NULL --登记时间
)

我想按照 qkts 统计下,大概效果如下
单位代码 单位名称 0-30天 30-60天 60-90天... 330-360天 360天以上 合计
31-AC   单位2  2019.58 -99.90 -99.90 ...  0.00     0.00    1819.78      
33-AC   单位1  2019.58 -99.90 -99.90 ...  0.00     0.00    1819.78
就是取对应的qkts在0-30内djsj最大所对应的qk,qkts在30-60内djsj最大所对应的qk,qkts在60-90内djsj最大所对应的qk....

测试数据如下

insert into tbName 
select '31-AC','单位2', 1535.26, 34, '2010-03-01 00:01:46.217' union all
select '33-AC','单位1', -99.90, 42, '2010-03-01 00:01:46.217' union all
select '33-AC','单位1', -99.90, 43, '2010-03-02 00:01:46.420' union all
select '31-AC','单位2', 1535.26, 35, '2010-03-02 00:01:46.420' union all
select '33-AC','单位1', 1535.26, 36, '2010-03-03 00:01:47.077' union all
select '33-AC','单位1', -99.90, 44, '2010-03-03 00:01:47.077' union all
select '33-AC','单位1', -99.90, 45, '2010-03-04 00:02:01.857' union all
select '33-AC','单位1', 1535.26, 37, '2010-03-04 00:02:01.857' union all
select '31-AC','单位2', 1535.26, 38, '2010-03-05 00:01:50.263' union all
select '33-AC','单位1', -99.90, 46, '2010-03-05 00:01:50.263' union all
select '33-AC','单位1', -99.90, 47, '2010-03-06 00:02:57.450' union all
select '31-AC','单位2', 1535.26, 39, '2010-03-06 00:02:57.450' union all
select '33-AC','单位1', 1535.26, 40, '2010-03-07 00:01:49.623' union all
select '33-AC','单位1', -99.90, 48, '2010-03-07 00:01:49.623' union all
select '33-AC','单位1', 1535.26, 41, '2010-03-08 00:01:48.107' union all
select '31-AC','单位2', -99.90, 49, '2010-03-08 00:01:48.107' union all
select '33-AC','单位1', 1535.26, 42, '2010-03-09 00:01:49.247' union all 
select '33-AC','单位1', -99.90, 50, '2010-03-09 00:01:49.247' union all
select '33-AC','单位1', -99.90, 51, '2010-03-10 00:01:48.590' union all
select '31-AC','单位2', 1535.26, 43, '2010-03-10 00:01:48.590' union all
select '33-AC','单位1', 1535.26, 44, '2010-03-11 00:01:48.530' union all
select '33-AC','单位1', -99.90, 52, '2010-03-11 00:01:48.530' union all
select '33-AC','单位1', -99.90, 53, '2010-03-12 00:01:49.233' union all
select '33-AC','单位1', 1535.26, 45, '2010-03-12 00:01:49.233' union all 
select '31-AC','单位2', 1535.26, 46, '2010-03-13 00:01:48.437' union all
select '33-AC','单位1', -99.90, 54, '2010-03-13 00:01:48.437' union all
select '33-AC','单位1', 1535.26, 47, '2010-03-14 00:01:46.670' union all
select '31-AC','单位2', -99.90, 55, '2010-03-14 00:01:46.670' union all
select '33-AC','单位1', -99.90, 56, '2010-03-15 00:01:46.530' union all
select '33-AC','单位1', 1535.26, 48, '2010-03-15 00:01:46.530' union all
se