首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据列值从另一个表调用值

根据列值从另一个表调用值
EN

Stack Overflow用户
提问于 2020-07-03 23:00:07
回答 2查看 43关注 0票数 0

我有两个表,如下所示

代码语言:javascript
复制
table 1
-------   
type_id   type_title
=======   ===========
      1   Zoning District  
      2   Parcel_ID  
      3   CC Districts


table 2
-------   
location _id  type_id   store_value
============  =======   ===========
        6846        1   E - Big South  
        6846        2   L3300
        6846        3   

我想要显示以下输出

代码语言:javascript
复制
location_id  Parcel_ID  Zoning_Districts  CC_Districts
===========  =========  ================  ============
       6846  L3300      E - Big South
EN

回答 2

Stack Overflow用户

发布于 2020-07-03 23:08:57

连接表并使用条件聚合:

代码语言:javascript
复制
select t2.location_id,
  max(case when t1.type_title = 'Parcel_ID' then t2.store_value end) Parcel_ID,  
  max(case when t1.type_title = 'Zoning District' then t2.store_value end) Zoning_Districts,
  max(case when t1.type_title = 'CC Districts' then t2.store_value end) CC_Districts  
from table2 t2 left join table1 t1
on t1.type_id = t2.type_id
group by t2.location_id

请参阅demo

结果:

代码语言:javascript
复制
| location_id | Parcel_ID | Zoning_Districts | CC_Districts |
| ----------- | --------- | ---------------- | ------------ |
| 6846        | L3300     | E - Big South    |              |
票数 0
EN

Stack Overflow用户

发布于 2020-07-03 23:21:37

代码语言:javascript
复制
;with location_cte
AS(
SELECT DISTINCT locationId
FROM table2
)
SELECT locationId,
(Select store_value FROM table2 t Where t.locationId = c.locationId And typeId =2),
...
...
...
FROM location_cte c

您需要从表2中获取所有不同的位置,然后对每一列执行一个查询。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62718052

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档