select 语句中用到判断

lj198608025715 2010-06-07 08:26:19
FID FType Famount fcust
1 3 100 111
2 5 200 111
3 3 400 111
4 5 500 111

例如这个表,我需要查询出来一个结果值,就是111这个客户,当Ftype=3时,减去相应的Famount值,当Ftype =5 时,加上相应的Famount值,最后结果得到一个Sum值,怎么写呢?用CASE么
...全文
73 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
htl258_Tony 2010-06-07
  • 打赏
  • 举报
回复
--如果不显示FCUID,直接:

-->SQL查询如下:
SELECT
SUM(
CASE ftype
WHEN 3 THEN - Famount
WHEN 5 THEN Famount
ELSE 0
END
) Famount
FROM tb
WHERE [fcust] = 111

/*
Famount
-----------
200

(1 行受影响)
*/
lj198608025715 2010-06-07
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 htl258 的回复:]
SQL code
select fcust,sum(case ftype when 3 then - Famount else Famount end) Famount
from tb
where ftype in(3,5)
group by fcust
[/Quote]
好帅气,谢谢
htl258_Tony 2010-06-07
  • 打赏
  • 举报
回复
--> 生成测试数据表: [tb]
IF OBJECT_ID('[tb]') IS NOT NULL
DROP TABLE [tb]
GO
CREATE TABLE [tb] ([FID] [int],[FType] [int],[Famount] [int],[fcust] [int])
INSERT INTO [tb]
SELECT '1','3','100','111' UNION ALL
SELECT '2','5','200','111' UNION ALL
SELECT '3','3','400','111' UNION ALL
SELECT '4','5','500','111'

--SELECT * FROM [tb]

-->SQL查询如下:
SELECT fcust,
SUM(
CASE ftype
WHEN 3 THEN - Famount
WHEN 5 THEN Famount
ELSE 0
END
) Famount
FROM tb
WHERE [fcust] = 111
GROUP BY fcust
/*
fcust Famount
----------- -----------
111 200

(1 行受影响)
*/
永生天地 2010-06-07
  • 打赏
  • 举报
回复
select sum(case FType when 5 then Famount else -Famount end)
from tb where fcust='111'
rmljoe 2010-06-07
  • 打赏
  • 举报
回复
select
fcust,
sum(case ftype when 3 then -Famount else famount end) as total
from
tb
group by
fcust
htl258_Tony 2010-06-07
  • 打赏
  • 举报
回复
select fcust,sum(case ftype when 3 then - Famount else Famount end) Famount 
from tb
where ftype in(3,5)
group by fcust
lj198608025715 2010-06-07
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 wufeng4552 的回复:]
么懂
结果是什么.
[/Quote]
上面的例子结果是500-400+200-100
水族杰纶 2010-06-07
  • 打赏
  • 举报
回复
么懂
结果是什么.

34,575

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧