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

sql按月份区间查询记录
表是这样的:
车型 年份 1月 2月 3月 4月 5月 6月 7月 8月 9月 10月 11月 12月

suv 2003 1 6 2 2 4 0 1 0 3 0 1 2

ft 2003 3 2 1 3 3 1 0 0 1 2 3 0

asd 2004 2 1 0 0 2 4 1 0 2 3 2 0

输入两个参数 比如 2003年6月 至 2004年3月 怎么查出这期间的记录?




------解决方案--------------------
SQL code
--> 测试数据:[tb]
IF OBJECT_ID('[tb]') IS NOT NULL DROP TABLE [tb]
GO 
CREATE TABLE [tb]([车型] VARCHAR(3),[年份] INT,[1月] INT,[2月] INT,[3月] INT,[4月] INT,[5月] INT,[6月] INT,[7月] INT,[8月] INT,[9月] INT,[10月] INT,[11月] INT,[12月] INT)
INSERT [tb]
SELECT 'suv',2003,1,6,2,2,4,0,1,0,3,0,1,2 UNION ALL
SELECT 'ft',2003,3,2,1,3,3,1,0,0,1,2,3,0 UNION ALL
SELECT 'asd',2004,2,1,0,0,2,4,1,0,2,3,2,0
--------------开始查询--------------------------
declare @begin_date datetime,@end_date datetime
set @begin_date= '2003-6-01'
set @end_date='2004-03-01'
select [车型],sum([num])
from
(
    SELECT [车型],[日期]=convert(varchar(10),ltrim([年份])+'-'+replace([month],'月','-01'),120),[num] FROM [tb]
    UNPIVOT ([num] FOR [month] IN 
                    ([1月], [2月], [3月], [4月], [5月], [6月], [7月], [8月], [9月], [10月], [11月], [12月]) 
            )unp
) t 
where [日期] between @begin_date and @end_date
group by [车型]


----------------结果----------------------------
/* 
车型    (无列名)
asd    3
ft    7
suv    7
*/

------解决方案--------------------
SQL code

create table b2
(车型 varchar(5), 年份 int, 
 [1月] int, [2月] int, [3月] int, [4月] int,
 [5月] int, [6月] int, [7月] int, [8月] int,
 [9月] int, [10月] int, [11月] int, [12月] int)
 
insert into b2
select 'suv', 2003, 1, 6, 2, 2, 4, 0, 1, 0, 3, 0, 1, 2 union all
select 'ft', 2003, 3, 2, 1, 3, 3, 1, 0, 0, 1, 2, 3, 0 union all
select 'asd', 2004, 2, 1, 0, 0, 2, 4, 1, 0, 2, 3, 2, 0


--输入两个参数
declare @p1 varchar(10),@p2 varchar(10)

select @p1='2003年6月',@p2='2004年3月';

--查出这期间的记录
with t as
(select 车型,年份,u.col,u.val
 from b2 b 
 unpivot(val for col in
  ([1月],[2月],[3月],[4月],
   [5月],[6月],[7月],[8月],
   [9月],[10月],[11月],[12月])) u
)
select * from t
where cast(rtrim(年份)+'/'+replace(col,'月','')+'/01' as date)
between cast(replace(replace(@p1,'年','/'),'月','/01') as date)
and cast(replace(replace(@p2,'年','/'),'月','/01') as date);

/*
车型    年份          col        val
----- ----------- ---------- -----------
suv   2003        6月         0
suv   2003        7月         1
suv   2003        8月         0
suv   2003        9月         3
suv   2003        10月        0
suv   2003        11月        1
suv   2003        12月        2
ft    2003        6月         1
ft    2003        7月         0
ft    2003        8月         0
ft    2003        9月         1
ft    2003        10月        2
ft    2003        11月        3
ft    2003        12月        0
asd   2004        1月         2
asd   2004        2月         1
asd   2004        3月         0

(17 row(s) affected)
*/