请在下面找到表格结构
table A Table B
10 10
20 10
30 0
40 0
我想分开A / B. 如果有30/0我想把它显示为0。
我希望像
一样输出O/P
1
2
0
0
我们怎么能这样做?
Table structure queries:
create table #test1(id int)
insert into #test1 values(10)
insert into #test1 values(20)
insert into #test1 values(30)
insert into #test1 values(40)
select top 100 * from #test1
create table #test2(id int)
insert into #test2 values(10)
insert into #test2 values(10)
insert into #test2 values(0)
insert into #test2 values(0)
select top 100 * from #test2
答案 0 :(得分:1)
试试这个
SELECT A.id,B.id, IIF(B.id<>0,A.Id/B.ID,0) AS ExpectedResult,
COALESCE( A.id/NULLIF(B.ID,0),0) AS ExpectedResult2
FROM
(
SELECT Id,ROW_NUMBER()OVER(Order BY ID) As Seq FROM #test1
)As A
INNER JOIN
(
SELECT Id,ROW_NUMBER()OVER(Order BY ID DESC) As Seq FROM #test2)AS B
ON A.Seq=B.Seq
结果
id id ExpectedResult ExpectedResult2
10 10 1 1
20 10 2 2
30 0 0 0
40 0 0 0
答案 1 :(得分:0)
尝试此查询:
select A, B, case B when 0 then B else A/B end [A/B]
from (values (10,10),(20,10),(30,0),(40,0)) tbl(A,B)
以上查询使用case
语句在0
时返回B = 0
并在B <> 0
时分开。