日期:2014-05-18  浏览次数:20442 次

按日期分组
现在要从一张表里面取出记录按照时期来分组。
必然说我要取得表里面客户的从1月12月的所有记录,该怎么做?

另外,如果要求出每个客户从1月到12的记录,该怎么做?
select   a.CustomerName,isnull(b.TotalPiece,0)   as   TotalPiece,isnull(b.TotalMoney,0)   AS   TotalMoney
from
(select   distinct     CustomerName   from   TQof
where     CompanyID= '100001 '   )   a
left   join  
(
select   CustomerName,Count(*)   AS   TotalPiece,SUM(TotalMoney)   AS   TotalMoney
from   TQof
Group   by   CustomerName
)   b
on   a.CustomerName   =b.CustomerName
上面这个是用来取出所有客户的总金额,总数目的SQL,如果客户总金额或者总数目为0那也可以显示出来,就是0。
谢谢啦。

------解决方案--------------------
--try


select CustomerName,
[1月金额]=sum(case when month(日期字段)=1 then TotalMoney else 0 end),
[2月金额]=sum(case when month(日期字段)=2 then TotalMoney else 0 end),
[3月金额]=sum(case when month(日期字段)=3 then TotalMoney else 0 end),
[4月金额]=sum(case when month(日期字段)=4 then TotalMoney else 0 end),
[5月金额]=sum(case when month(日期字段)=5 then TotalMoney else 0 end),
[6月金额]=sum(case when month(日期字段)=6 then TotalMoney else 0 end),

[7月金额]=sum(case when month(日期字段)=7 then TotalMoney else 0 end),
[8月金额]=sum(case when month(日期字段)=8 then TotalMoney else 0 end),
[9月金额]=sum(case when month(日期字段)=9 then TotalMoney else 0 end),
[10月金额]=sum(case when month(日期字段)=10 then TotalMoney else 0 end),
[11月金额]=sum(case when month(日期字段)=11 then TotalMoney else 0 end),
[12月金额]=sum(case when month(日期字段)=12 then TotalMoney else 0 end),

Count(*) AS TotalPiece,
isnull(SUM(TotalMoney), 0) AS TotalMoney
from TQof
where year(日期字段)=2006 and CompanyID= '100001 '
Group by CustomerName
------解决方案--------------------
樓上.
------解决方案--------------------
假设表结构为ID,DATE,NUMBER
以下为按月份分组

select substring(convert(varchar(10),date,120),6,2) as date, sum(number) as number
from tb
group by substring(convert(varchar(10),date,120),6,2)

以下为按每人每月份分组
select id , substring(convert(varchar(10),date,120),6,2) as date, sum(number) as number
from tb
group by id , substring(convert(varchar(10),date,120),6,2)