如何用sql的日期函数,分别查出1月~12月每个月的销售金额?

2024-11-28 01:50:23
推荐回答(2个)
回答(1):

一般情况下数据是按日期存到数据库中的,但考虑到某些月份是无数据的,可用如下语句:

1、创建测试表及插入测试数据:

create table sale

(id int,

name varchar(10),

sdate datetime,

money int)


insert into sale values (1,'西瓜','2015-01-01',10)

insert into sale values (2,'香蕉','2015-01-05',20)

insert into sale values (3,'苹果','2015-02-01',60)

insert into sale values (4,'葡萄','2015-02-23',345)

insert into sale values (5,'柚子','2015-04-23',10)

insert into sale values (6,'牛奶','2015-05-12',67)

insert into sale values (7,'地瓜','2015-06-01',10)

insert into sale values (8,'土豆','2015-07-01',10)


2、执行语句:

with t as

( select '2015-'+right('0'+cast(number+1 as varchar),2) number from master..spt_values where type='p' and number<=11 )

select t.number month,SUM(isnull(b.money,0)) money 

from t left join sale b on 

t.number=CONVERT(varchar(7),b.sdate,120)

group by t.number


结果截图:

回答(2):

  /*
  分别查出1月~12月每个月的销售金额
  */

  --12个月总是固定的
  DECLARE @sale TABLE(ddate DATETIME,fsale DECIMAL(18,2))
  INSERT INTO @sale(ddate,fsale)
  SELECT '2010-10-11',10000.01 UNION ALL
  SELECT '2010-10-12',20000.02 UNION ALL
  SELECT '2010-09-01',55555.11 UNION ALL
  SELECT '2010-08-21',33333.33 UNION ALL
  SELECT '2009-12-11',77777.11

  SELECT SUM(CASE WHEN MONTH(s.ddate) = 1 THEN s.fsale ELSE 0 END) AS '一月',
  SUM(CASE WHEN MONTH(s.ddate) = 2 THEN s.fsale ELSE 0 END) AS '二月',
  SUM(CASE WHEN MONTH(s.ddate) = 3 THEN s.fsale ELSE 0 END) AS '三月',
  SUM(CASE WHEN MONTH(s.ddate) = 4 THEN s.fsale ELSE 0 END) AS '四月',
  SUM(CASE WHEN MONTH(s.ddate) = 5 THEN s.fsale ELSE 0 END) AS '五月',
  SUM(CASE WHEN MONTH(s.ddate) = 6 THEN s.fsale ELSE 0 END) AS '六月',
  SUM(CASE WHEN MONTH(s.ddate) = 7 THEN s.fsale ELSE 0 END) AS '七月',
  SUM(CASE WHEN MONTH(s.ddate) = 8 THEN s.fsale ELSE 0 END) AS '八月',
  SUM(CASE WHEN MONTH(s.ddate) = 9 THEN s.fsale ELSE 0 END) AS '九月',
  SUM(CASE WHEN MONTH(s.ddate) = 10 THEN s.fsale ELSE 0 END) AS '十月',
  SUM(CASE WHEN MONTH(s.ddate) = 11 THEN s.fsale ELSE 0 END) AS '十一月',
  SUM(CASE WHEN MONTH(s.ddate) = 12 THEN s.fsale ELSE 0 END) AS '十二月'
  FROM @sale AS s
  WHERE YEAR(s.ddate) = 2010