根据不同的标准选择每个列值

时间:2011-11-05 09:32:13

标签: sql sql-server sql-server-2005

我有一个SQL查询,如下所示:

SELECT urban_appr, urban_in, rural_appr, rural_in, ground_appr, ground_in 
FROM <table>

在上面的查询中,我必须按如下方式添加WHERE子句:

  • 对于城市价值观,WHERE scheme_type = 'U'
  • 对于农村价值观,WHERE scheme_type = 'R'
  • 对于地面值,WHERE scheme_type = 'E'

我希望所有这些都使用单个SQL查询。我正在使用SQL Server 2005。

编辑:

在实际问题下面添加了图片。您可以看到它将区域BR显示为两条记录,而我希望它在一行中。

enter image description here

3 个答案:

答案 0 :(得分:2)

使用JOIN将每个district_nm的所有行合并为一行:

select
    district_nm,
    t1.urban_appr, t1.urban_in,
    t2.rural_appr, t2.rural_in,
    t3.ground_appr, t3.ground_in
from <table> t1
join <table> t2 on t2.district_nm = t1.district_nm and t2.scheme_type = 'R'
join <table> t3 on t3.district_nm = t1.district_nm and t3.scheme_type = 'E'
where t1.scheme_type = 'U';

您可以根据需要向where子句添加更多条件,例如and t1.district_nm = 'x'

考虑从上面的查询创建一个视图,并在我们的应用程序中使用它:

create view table_view as
<above query>

答案 1 :(得分:1)

嗯,这看起来很难看 - 但试试这个......

SELECT ISNULL(district_nm,nm) district_nm,
  URBAN_APPR,
  URBAN_IN,
  RURAL_APPR,
  RURAL_IN,
  ground_appr,
  ground_in
FROM
  (SELECT ISNULL(a.district_nm, b.district_nm) nm,
    urban_appr,
    urban_in,
    rural_appr,
    rural_in
  FROM
    (SELECT DISTRICT_NM,
      URBAN_APPR,
      URBAN_IN
    FROM TABLE_NAME
    WHERE SCHEME_TYPE = 'U'
    ) a
  FULL OUTER JOIN (
    (SELECT DISTRICT_NM,
      RURAL_APPR,
      RURAL_IN
    FROM TABLE_NAME
    WHERE SCHEME_TYPE = 'R'
    )B)
  ON a.district_nm = b.district_nm
  ) temp
FULL OUTER JOIN (
  (SELECT DISTRICT_NM,
    GROUND_APPR,
    GROUND_IN
  FROM TABLE_NAME
  WHERE SCHEME_TYPE = 'E'
  )c)
ON temp.nm = c.district_nm; 

答案 2 :(得分:1)

您是否尝试执行此类操作 - 根据值的类型选择不同的列?

SELECT urban_appr, urban_in, NULL, NULL, NULL, NULL
FROM dbo.YourTable WHERE scheme_type = 'U'
UNION
SELECT NULL, NULL, rural_appr, rural_in, NULL, NULL
FROM dbo.YourTable WHERE scheme_type = 'R'
UNION
SELECT NULL, NULL, NULL, NULL, ground_appr, ground_in
FROM dbo.YourTable WHERE scheme_type = 'E'

???

更新,因此您希望通过它添加其他列和组:

SELECT district_nm, urban_appr, urban_in, NULL, NULL, NULL, NULL
FROM dbo.YourTable WHERE scheme_type = 'U'
UNION
SELECT district_nm, NULL, NULL, rural_appr, rural_in, NULL, NULL
FROM dbo.YourTable WHERE scheme_type = 'R'
UNION
SELECT district_nm, NULL, NULL, NULL, NULL, ground_appr, ground_in
FROM dbo.YourTable WHERE scheme_type = 'E'
GROUP BY district_nm

这就是你要找的东西吗?