2013-03-15 4 views
0

의 날짜 필드와 달의 목록을 비교하면이 같다 :내가 내 데이터베이스에 테이블이 SQL 서버 2008 를 사용하고 테이블

table

내가 원하는 같은 출력 :

enter image description here

내 테이블에 나와 있듯이 smalldatetime 데이터 형식과 과일 및 vegi 필드가있는 DateField가 있습니다. 월별 데이터를 보여주는 출력을 원합니다. 월간 비교는 내 테이블의 DateField를 기반으로 수행해야합니다. (이 문제가 발생하는 것으로 어떤 SQL 바이올린)

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] 

전체 테스트 세부 사항 :

+0

@Mahmoud 가말은 PLZ이 나를 ​​도움이됩니다. –

답변

1

당신은 같은 것을 사용할 수 있습니다

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