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

SQL统计数量问题
表中有P_Money(金额),P_InTime(时间),Shop_ID(门店编号),P_PayType(付款类型)四列

下面代码是要查询某个门店某个类型一年每个月的销售额是多少,没有月记录的也要求能查询出来,不过为0 

select m.month , isnull(n.P_Money,0) P_Money from
(
select 1 month union
select 2 month union
select 3 month union
select 4 month union
select 5 month union
select 6 month union
select 7 month union
select 8 month union
select 9 month union
select 10 month union
select 11 month union
select 12 month 
) m
left join
(select datepart(mm,P_InTime) P_InTime , sum(P_Money) P_Money from Pay_View where datediff(yy,P_InTime,getdate()) = 0 group by datepart(mm,P_InTime)) n
on m.month = n.P_InTime

 

查询结果:

1 0
2 0
3 0
4 0
5 0
6 0
7 0
8 0
9 0
10 30
11 30
12 40


如何将上面的代码改为查询一年12个月每个月的数量,不统计总金额了,就统计付款次数,怎么改为统计?

------解决方案--------------------
--sum(P_Money) 改為 count(P_Money)

統計次數
------解决方案--------------------
确认以下查询是否有数据?
SQL code
select * from DingDan where TaoXi_ID=100003 and datediff(yy,D_Time1,getdate()) = 0