从多个表中选择多个列

时间:2013-03-21 10:53:10

标签: sql sql-server sql-server-2008 sql-server-2008-r2

实施例。
我有两张桌子

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

如何在一个选择查询中得到这个?

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

3 个答案:

答案 0 :(得分:0)

理想情况下,car_info表中应该有一个列,用于指定该行上显示的信息类型。即类型1是年份,类型2是国家。

你可以通过加入car_info表两次来指明连接上的“AND”条件,如下所示:

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'

答案 1 :(得分: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'
;

答案 2 :(得分: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

中的演示