[英]Call value from another table based on a column value
I have two tables as shown below我有两个表,如下所示
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
I would like to display the following output我想显示以下 output
location_id Parcel_ID Zoning_Districts CC_Districts
=========== ========= ================ ============
6846 L3300 E - Big South
Join the tables and use conditional aggregation:加入表并使用条件聚合:
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
See the demo .见演示。
Results:结果:
| location_id | Parcel_ID | Zoning_Districts | CC_Districts |
| ----------- | --------- | ---------------- | ------------ |
| 6846 | L3300 | E - Big South | |
;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
You need fetch all distinct location from table 2 then for each column have a query.您需要从表 2 中获取所有不同的位置,然后对每一列进行查询。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.