数据库->SQL Server2005->第4季SQL从入门到提高->11练习和12练习1
//--------------------------------练习1
将这这张表
单号 金额
RK1 10
RK2 20
RK3 -30
RK4 -10
查询后输出如下结果:
单号 收入 支出
RK1 10 0
RK2 20 0
RK3 0 30
RK4 0 10
解题思路:
用流控函数,解题代码,
select FNumber as 单号,
(
case
when FAmount>0 then FAmount
else 0
end
) as 收入,
(
case
when FAmount<0 then abs(FAmount)
else 0
end
)as 支出
from T_Test1
(
case
when FAmount>0 then FAmount
else 0
end
) as 收入,
(
case
when FAmount<0 then abs(FAmount)
else 0
end
)as 支出
from T_Test1
//----------------------------------------- 练习2
表数据如下:
查询结果如下:
实现代码:
首先,看到这样的结果,
select Name,(
case
when Score=N'胜' then 1
else 0
end
)as 胜,
(
case
when Score=N'负' then 1
else 0
end
)as 负
from T_Scores
再是最终结果,
select Name,
sum((
case
when Score=N'胜' then 1
else 0
end
))as 胜,
sum((
case
when Score=N'负' then 1
else 0
end
))as 负
from T_Scores group by Name
sum((
case
when Score=N'胜' then 1
else 0
end
))as 胜,
sum((
case
when Score=N'负' then 1
else 0
end
))as 负
from T_Scores group by Name
合乎自然而生生不息。。。