如何查询将数据用作列名/字段名的表

时间:2014-04-22 03:45:02

标签: sql sql-server pivot

说我有这张桌子:

Day     AMFrom      AMTo        PMfrom      PMTo
--------------------------------------------------------------------
Monday      09:00       Null        Null        06:00
Tuesday     09:00       Null        Null        06:00
Wednesday   09:00       Null        Null        06:00
Thursday    09:00       Null        Null        06:00
Friday      09:00       Null        Null        06:00
Saturday    08:00       Null        Null        05:00
Friday      08:00       Null        Null        06:00

如何查询此表以获得此类输出:

MondayAMFrom        MondayAMTo  MondayPMFrom        MondayPMTo
--------------------------------------------------------------------------
09:00               NULL        Null                06:00

输出还包括TuesdayAMFrom, TuesdayPMto,.......... SundayPMTo.

2 个答案:

答案 0 :(得分:2)

试试这个

DECLARE @sql AS varchar(max)
DECLARE @Day AS varchar(max)
SET  @Day = 'Monday'

SET @sql = 'SELECT AMFrom As ' + @Day + 'AMFrom,
                   AMTo As ' + @Day + 'AMTo,
                   PMFrom As '+ @Day + 'PMFrom,
                   PMTo As ' + @Day + 'PMTo
            FROM Table1
 WHERE Day = ''' + @Day+ ''''

 Exec(@sql)

<强> Fiddle Demo

答案 1 :(得分:2)

我简化了架构以简化,但它也可以应用于您的架构:

create table tbl(day varchar(20), amfrom int, amto int);
insert into tbl values ('Monday', 9, null);
insert into tbl values ('Tuesday', 10, 11);

select 
  MondayAmFrom,
  MondayAmTo,
  TuesdayAmFrom,
  TuesdayAmTo
from 
(
  select
    amfrom as MondayAmFrom,
    amto as MondayAmTo
  from tbl where day = 'Monday'
) as mon
,  
(
    select 
      amfrom as TuesdayAmFrom,
      amto as TuesdayAmTo
    from tbl where day = 'Tuesday'
 ) as tue;

这是输出:

MONDAYAMFROM MONDAYAMTO TUESDAYAMFROM TUESDAYAMTO
9            (null)     10            11

我们创建每天选择的子查询。然后我们将他们加入主表。需要知道一周中的几天,在您的示例中就是这种情况。只有7个。

Select case when then在这里不起作用,因为它会创建7行,并且很难对它们进行分组。分组的问题是您的模式支持空值。

SQLFiddle Link