質問

Say I have this table:

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

How can I query this table to have this kind of output:

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

The output also includes TuesdayAMFrom, TuesdayPMto,.......... SundayPMTo.

役に立ちましたか?

解決

I simplified the schema for brevity but it can be applied to your schema as well:

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;

This is the output:

MONDAYAMFROM MONDAYAMTO TUESDAYAMFROM TUESDAYAMTO
9            (null)     10            11

We create subqueries selecting each day. Then we join them in the main table. The days of the week need to be known which is the case in your example. There are only 7 of them.

Select case when then will not work here because it will create 7 rows and it will be difficult to group them. The problem with grouping is that your schema supports nulls.

SQLFiddle Link

他のヒント

Try this

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

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top