0

例。
私は2つのテーブルを持っています

CAR
id  name
1    bmw
2    fiat

Car_info
car_id  field_name   country
  1     year          2000
  1     country       germany
  2     year          1988
  2     country       italy

1つの選択クエリでこれを取得するにはどうすればよいですか?

id name  year  country
1   bmw  2000   germany
2   fiat 1988   italy
4

3 に答える 3

0
WITH car AS (
  SELECT 1 AS id, 'BMW' AS name FROM dual
  UNION ALL
  SELECT 2, 'Fiat' FROM dual
)
, car_info AS (
  SELECT 1 AS car_id, 'Year' AS field_name, '2000' AS field_val FROM dual
  UNION ALL
  SELECT 1, 'Country', 'Germany' FROM dual
  UNION ALL
  SELECT 2, 'Year', '1988' FROM dual
  UNION ALL
  SELECT 2, 'Country', 'Italy' FROM dual
)
  SELECT c.*, car_year.field_val AS yr, car_country.field_val AS country
    FROM car c
    JOIN car_info car_year ON c.id = car_year.car_id AND car_year.field_name = 'Year'
    JOIN car_info car_country ON c.id = car_country.car_id AND car_country.field_name = 'Country'
;
于 2013-03-21T11:09:07.493 に答える
0

これを試してください:テーブルを使用PIVOTして結合できますCar

with cte as 
(
 Select car_id,[year],[country]
 from 
 (Select car_id,field_name,countryName
  from car_info
 )pv
 pivot 
 (
  max(countryName)
  FOR field_name IN ([year],[country])
 )pvt
 )
 Select c.name,ct.year,ct.country
 from car c inner join cte ct
 on ct.car_id=c.id

SQL Fiddleでのデモ

于 2013-03-21T11:09:42.920 に答える
0

理想的には、car_info テーブルに、その行に表示される情報の種類を指定する列が必要です。つまり、タイプ 1 は年、タイプ 2 は国です。

次のように、結合に「AND」条件を指定して car_info テーブルに 2 回結合することで、これを回避できます。

SELECT car.ID, car.Name, ci1.country as [YEAR], ci2.country as COUNTRY
FROM car
INNER JOIN car_info AS ci1 ON Car.ID = ci1.car_id AND ci1.field_name = 'year'
INNER JOIN car_info AS ci2 ON Car.ID = ci2.car_id AND ci2.field_name = 'country'
于 2013-03-21T11:07:32.403 に答える