0

我正在使用 sql server 2008 我的数据库中的表是这样的:

桌子

我想要这样的输出:

在此处输入图像描述

正如我的表中所示,我有 DateField,它具有 smalldatetime 数据类型以及水果和蔬菜字段。我想要这样的输出,它显示每月的数据。月份比较应该基于我的表的 DateField 进行。

4

1 回答 1

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 Fiddle,因为它遇到了问题):

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]

在此处输入图像描述

于 2013-03-15T10:32:47.430 回答