【问题标题】:Complicated Sql join query with some condition to get one of the column具有某些条件的复杂 Sql 连接查询以获取列之一
【发布时间】:2017-09-06 07:31:21
【问题描述】:

我有两张桌子

表1:

Id | product | price
---+---------+------
1  |    A    |  5 
1  |    B    |  3
1  |    C    |  6

表2:

Id | prod | subprod
---+------+--------
1  |  A   |  xxxx
1  |  A   |  yyyy
1  |  A   |  zzzz

我的结果表应该包含 table2 中的所有 3 行以及一个名为 price 的新列(将从 table1 计算值)

结果表应该是这样的

Id|prod|subprod|price
--+----+-------+-----
1 | A  | xxxx  |(if subprod = xxxx in table 2 then this should have price of A from table 1)
1 | A  | yyyy  |(if subprod = yyyy in table 2, then if price of B is greater than price of C then the value should be price of B else 0)
1 | A  | zzzz  |(if subprod = zzzz in table 2, then if price of B is less than price of C then the value should be price of C-B else 0) 

【问题讨论】:

  • 你想要整个 if 语句在你的输出中,还是你想要 if 语句的解决方案?到目前为止,您还尝试过什么?发布您的查询
  • 看起来像家庭作业
  • @RealCheeseLord 我创建了一个函数,所有这些都是硬编码的,并且每次在查询中调用它
  • @RuslanK。这是真正的工作问题……不是在家工作。

标签: sql-server sql-server-2008 sql-server-2014 sql-server-2016


【解决方案1】:

试试这个:

select distinct tab_2.*,case when tab_2.subprod ='xxxx' then (select tab_1.price from tab_1 where product='A') 
 when tab_2.subprod ='yyyy' then CASE WHEN  ( select price from tab_1 where product='B') > ( select price from tab_1 where product='C') THEN ( select price from tab_1 where product='B') else 0 end
 when tab_2.subprod ='zzzz' then CASE WHEN  ( select price from tab_1 where product='B') < ( select price from tab_1 where product='C') THEN ( select price from tab_1 where product='C') - ( select price from tab_1 where product='B') else 0 end
 END AS price
from tab_1,tab_2
where tab_1.Id =tab_2.id

输出:-

id  prod    subprod     price
1   A       xxxx        5
1   A       yyyy        0
1   A       zzzz        3

编辑:

 select distinct tab_2.*,case when tab_2.subprod ='xxxx' then (select tab_1.price from tab_1 where product='A') 
 when tab_2.subprod ='yyyy' then CASE WHEN  b.price > c.price THEN b.price else 0 end
 when tab_2.subprod ='zzzz' then CASE WHEN  b.price < c.price THEN c.price - b.price else 0 end
 END AS price
from tab_1,tab_2,( select id,price from tab_1 where product='B') b,( select id,price from tab_1 where product='C')c
where tab_1.Id =tab_2.id
and b.id =tab_2.id
and c.Id =tab_2.id

【讨论】:

  • 这行得通.. 有没有一种方法可以更好地使用 cAse 语句。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-27
  • 1970-01-01
  • 2010-11-02
  • 1970-01-01
  • 2023-03-08
相关资源
最近更新 更多