我有以下数据。
输出:
id cid price sold
--------------------
1 1 10 20
2 1 30 40
3 2 50 60
我需要的是:
id cid Amount
--------------
1 1 20
2 1 10
3 2 30
如果id = cid
然后以其他方式出售
如果id != cid
则将cid的匹配ID的价格作为金额(请参考上面的输出,如果它令人困惑!)
我有以下SQL查询:
declare @tg table(id int, cid int, price int, sold int)
insert into @tg values(1, 1, 10, 20);
insert into @tg values(2, 1, 30, 40);
insert into @tg values(3, 2, 50, 60);
SELECT
id, cid,
CASE WHEN id = cid
THEN sold
WHEN B.id IN (SELECT
CASE WHEN id != cid
THEN cid
END AS cid1
FROM @tg A
WHERE A.cid = B.id)
THEN price
END as amount
FROM
@tg AS B
--OR
select
id,cid,
CASE WHEN id = cid THEN sold else price END as amount from @tg
as B
id != cid
时无效。
答案 0 :(得分:1)
select id,cid,case when id=cid then sold else (select price from @tg t1 where t1.id = t2.cid) end as amount
from @tg t2
我认为那就是你要找的东西,如果id = cid卖掉了,否则>从销售表中获取相应的价格,其中cid = id
答案 1 :(得分:1)
像这样修改SELECT
select id,cid, CASE WHEN id = cid THEN sold
WHEN id <> cid
THEN price
END as amount from @tg
as B
这将在id = cid
其他明智Prize
答案 2 :(得分:1)
select
id,
cid,
case when cid = id then sold
else (select price from @tg where id=c.cid )
end as amount
from @tg c
答案 3 :(得分:0)
我认为这更像是一个加入:
$ curl -H 'Host: git.niklasrosenstein.com' http://localhost:8080 -i
HTTP/1.1 302 Found
Date: Mon, 18 Jan 2016 14:29:08 GMT
Status: 302 Found
Connection: close
X-Frame-Options: SAMEORIGIN
X-XSS-Protection: 1; mode=block
X-Content-Type-Options: nosniff
Location: http://niklasrosenstein.com
Content-Type: text/html; charset=utf-8
Cache-Control: no-cache
X-Request-Id: 1a63e4a4-a5fe-4544-8f74-8b1bd0117a57
X-Runtime: 0.271394
<html><body>You are being <a href="http://niklasrosenstein.com">redirected</a>.</body></html>
您只是在同一个表中查找该值。您实际上并不需要将select tg.*, tgc.price as sold
from @tg tg left join
@tg tgc
on tg.cid = tgc.id;
短路。
或者,如果您更喜欢子查询:
join
在这两种情况下,使用表别名很重要。否则,您无法区分临时表。