现有表
create table newsale
(city varchar(4),
date datetime,
money money,
valid char(1)
)
其中表valid用字符T和F来区分有效和无效交易现要求设计一个查询取出每年的每个月发生的有效交易和无效交易的笔数和总额,要求格式如下年/月 有效交易统计,无效交易统计,有效交易笔数,无效交易笔数
2005/09   1282.51         0           4            0
.
.
.
.
.
.我写的查询结构如下,
select  convert(char(4),datepart(yy,date))+'/'+convert(char(2),datepart(mm,date)) as [年/月],
sum(case valid when 'T' then money else 0 end) as 有效消费统计,
sum(case valid when 'F' then money else 0 end) as 无效消费统计,
sum(case valid when 'T' then 1 else 0 end) as 有效消费笔数,
sum(case valid when 'F' then 1 else 0 end) as 无效消费笔数
from  newsale
group by date
但确显示出2005/9  128.916         0.00 1 0
2005/9  270.4423 0.00 1 0
2005/9  658.8989 0.00 1 0
2005/9  224.2761 0.00 1 0
.
.
.
不知这该如何处理

解决方案 »

  1.   

    select  convert(char(4),datepart(yy,date))+'/'+convert(char(2),datepart(mm,date)) as [年/月],
    sum(case valid when 'T' then money else 0 end) as 有效消费统计,
    sum(case valid when 'F' then money else 0 end) as 无效消费统计,
    sum(case valid when 'T' then 1 else 0 end) as 有效消费笔数,
    sum(case valid when 'F' then 1 else 0 end) as 无效消费笔数
    from  newsale
    group by convert(char(4),datepart(yy,date))+'/'+convert(char(2),datepart(mm,date)) as [年/月]
      

  2.   

    select convert(char(7),getdate(),111) as [年/月],
    sum(case valid when 'T' then money else 0 end) as 有效消费统计,
    sum(case valid when 'F' then money else 0 end) as 无效消费统计,
    sum(case valid when 'T' then 1 else 0 end) as 有效消费笔数,
    sum(case valid when 'F' then 1 else 0 end) as 无效消费笔数
    from  newsale
    group by convert(char(7),getdate(),111)
      

  3.   

    --tryselect  convert(varchar(7),date,111)as [年/月],,sum(case valid when 'T' then money else 0 end) as 有效消费统计, 
    sum(case valid when 'F' then money else 0 end) as 无效消费统计, 
    sum(case valid when 'T' then 1 else 0 end) as 有效消费笔数, 
    sum(case valid when 'F' then 1 else 0 end) as 无效消费笔数 
    from  newsale 
    group by convert(varchar(7),date,111)
      

  4.   

    select convert(char(7),date,111) as [年/月],
    sum(case valid when 'T' then money else 0 end) as 有效消费统计,
    sum(case valid when 'F' then money else 0 end) as 无效消费统计,
    sum(case valid when 'T' then 1 else 0 end) as 有效消费笔数,
    sum(case valid when 'F' then 1 else 0 end) as 无效消费笔数
    from  newsale
    group by convert(char(7),date,111)
      

  5.   

    select  convert(char(4),datepart(yy,date))+'/'+convert(char(2),datepart(mm,date)) as [年/月], 
    sum(case valid when 'T' then money else 0 end) as 有效消费统计, 
    sum(case valid when 'F' then money else 0 end) as 无效消费统计, 
    sum(case valid when 'T' then 1 else 0 end) as 有效消费笔数, 
    sum(case valid when 'F' then 1 else 0 end) as 无效消费笔数 
    from  newsale 
    group by convert(char(4),datepart(yy,date))+'/'+convert(char(2),datepart(mm,date)) 
      

  6.   

    我还以为GROUP中只能写字段呢?原来是这个as有问题,啊!我又糊涂了一回结帐吧!