與表

2013-03-15 15 views
0

的日期字段比較月列表我使用SQL Server 2008 我的表在我的數據庫是這樣的:與表

table

而且我想這樣的輸出:

enter image description here

正如我的表所示,我有DateField其smalldatetime數據類型,以及水果和vegi領域。我想要顯示數據每月明智的輸出..月比較應根據我的表的DateField執行。

+0

@Mahmoud賈邁勒PLZ幫我在這。 – 2013-03-15 09:59:55

回答

1

您可以使用類似:

select [Month] = month(DateField) 
    , [MonthName] = left(datename(mm, DateField), 3) 
    , TotalAmountApple = sum(case when fruits = 'Apple' then 1 else 0 end) 
    , TotalAmountOnion = sum(case when vegi = 'Onion' then 1 else 0 end) 
from produce 
group by month(DateField) 
    , left(datename(mm, DateField), 3) 
order by [Month] 

完全測試的詳細信息(沒有SQL小提琴因爲它遇到的問題):

create table produce 
(
    id int 
    , fruits varchar(10) 
    , vegi varchar(10) 
    , DateField smalldatetime 
) 

insert into produce 
select 1, 'Apple', 'Chilly', '01-jan-2013' 
insert into produce 
select 1, 'Mango', 'Onion', '15-jan-2013' 
insert into produce 
select 1, 'Mango', 'Chilly', '20-jan-2013' 
insert into produce 
select 1, 'Apple', 'Chilly', '01-Feb-2013' 
insert into produce 
select 1, 'Mango', 'Onion', '15-Feb-2013' 
insert into produce 
select 1, 'Apple', 'Onion', '20-Feb-2013' 

select [Month] = month(DateField) 
    , [MonthName] = left(datename(mm, DateField), 3) 
    , TotalAmountApple = sum(case when fruits = 'Apple' then 1 else 0 end) 
    , TotalAmountOnion = sum(case when vegi = 'Onion' then 1 else 0 end) 
from produce 
group by month(DateField) 
    , left(datename(mm, DateField), 3) 
order by [Month] 

enter image description here