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

一个有点烦的SQL语句 分不同字段显示
有A表

ID zhuangtai jine  
1 1 800.414
2 1 300.423
3 0 3000.421
4 0 1000.531

要求查询显示  
zhuangtai 为0或1 时分别计算 金额字段 来显示 用SQL语句 或存储过程都行
保留两位小数 四舍五入 

状态1时 jine 状态0时 jine
1 1100.84 0 4000.95

------解决方案--------------------
SQL code


SELECT zhuantai,ROUND(SUM(jine),2) as jine
FROM  TableA
GROUP BY zhuantai

------解决方案--------------------
SQL code

SELECT
    状态1时 = 1,
    jine = SUM(CASE WHEN zhuangtai = 1 THEN jine END),
    状态0时 = 0,
    jine = SUM(CASE WHEN zhuangtai = 0 THEN jine END)
FROM A

------解决方案--------------------
SQL code
SELECT
    状态1时 = SUM(CASE WHEN zhuangtai = 1 THEN 1 END),
    jine = SUM(CASE WHEN zhuangtai = 1 THEN jine END),
    状态0时 = SUM(CASE WHEN zhuangtai = 0 THEN 1 END),
    jine = SUM(CASE WHEN zhuangtai = 0 THEN jine END)
FROM A

------解决方案--------------------
SQL code
SELECT
    状态1时 =SUM(CASE WHEN zhuangtai = 1 THEN 1 END),
    jine = cast(SUM(CASE WHEN zhuangtai = 1 THEN jine END) as decimal(10,2)),
    状态0时 =SUM(CASE WHEN zhuangtai = 0 THEN 1 END),
    jine = cast(SUM(CASE WHEN zhuangtai = 0 THEN jine END) as decimal(10,2))
FROM @t

------解决方案--------------------
引用楼主 lcaiyhh 的帖子:
有A表

ID zhuangtai jine
1 1 800.414
2 1 300.423
3 0 3000.421
4 0 1000.531

要求查询显示
zhuangtai 为0或1 时分别计算 金额字段 来显示 用SQL语句 或存储过程都行
保留两位小数 四舍五入

状态1时 jine 状态0时 jine
1 1100.84 0 4000.95

------解决方案--------------------
SQL code
create table tb(ID int,zhuangtai int, jine decimal(8,3))
insert into tb select 1,    1,        800.414 union all select 
2,    1,        300.423  union all select
3,    0,        3000.421  union all select
4,    0,        1000.531 union all select
5,    0,        100 
go
SELECT
    状态1时 = sum(case when zhuangtai=1 then 1 else 0 end),
    jine1 = cast(SUM(CASE WHEN zhuangtai = 1 THEN jine END)as decimal(8,2)),
    状态0时  = sum(case when zhuangtai=0 then 1 else 0 end),
    jine2 = cast(SUM(CASE WHEN zhuangtai = 0 THEN jine END) as decimal(8,2))
FROM tb

go
drop table tb
/*
状态1时        jine1                                   状态0时        jine2
----------- --------------------------------------- ----------- ---------------------------------------
2           1100.84                                 3           4100.95
*/