SQL Server 統計報表(不斷收藏中)

暖楓無敵發表於2012-07-01
create table #t (out_no varchar(10) primary key,date datetime,part varchar(30),qty numeric(12,4),price numeric(12,4))
insert into #t
select 'A01','2009-1-11','B001',100,1.1 union all
select 'A02','2009-1-12','B002',200,1.3 union all
select 'A03','2009-2-22','B003',120,1.5 union all
select 'A04','2009-3-22','B004',155,1.2 union all
select 'A05','2009-4-20','B005',600,1.6 union all
select 'A06','2009-4-22','B006',750,1.6 
--
--select * from #t

select
    月份='出貨數量',
    [1月]=sum(case when month(date)=1 then qty else 0 end),
    [2月]=sum(case when month(date)=2 then qty else 0 end),
    [3月]=sum(case when month(date)=3 then qty else 0 end),
    [4月]=sum(case when month(date)=4 then qty else 0 end),
    [5月]=sum(case when month(date)=5 then qty else 0 end)
from #t
union all
select
    月份='出貨金額',
    [1月]=sum(case when month(date)=1 then price*qty else 0 end),
    [2月]=sum(case when month(date)=2 then price*qty else 0 end),
    [3月]=sum(case when month(date)=3 then price*qty else 0 end),
    [4月]=sum(case when month(date)=4 then price*qty else 0 end),
    [5月]=sum(case when month(date)=5 then price*qty else 0 end)
from #t

/*
月份               1月                  2月                          3月                            4月                           5月
-------- --------------------------------------- --------------------------------------- --------------------------------------- ------------------------
出貨數量      300.0000           120.0000                  155.0000                 1350.0000                    0.0000
出貨金額      370.0000           180.0000                  186.0000                 2160.0000                    0.0000

(2 行受影響)
*/

drop table #t



2、

假設我們有一欄位名為name,其值是用逗號分隔的。

值為:'111,111xu2,1112'。

現在,我們需要編寫語句搜尋該name值 like '11'的。

按理說,這個name中沒有11,我們要的結果就是返回空。

但是如果我們 select * from student where name like '%11%'的話,依然可以正常的查詢出結果。

---

此時,我們應該採用如下的語句來實現:

 

select * from student where name like '%11%' --按照我的想法是不能查到的。但結果是查到了
--
解決辦法是:將sql欄位名前後加上,號,並且比較值前後也加上。
--
特別注意的是:欄位名加逗號時,要用字串連線的形式,不能直接 ',name,'
select * from student where ','+name+',' like '%,111,%'


相關文章