1

I have the following table with values as

CREATE TABLE stud 
  ( 
     sname NVARCHAR(10), 
     hr    NVARCHAR(30), 
     dt    DATETIME, 
     att   VARCHAR(3) 
  )

INSERT INTO stud VALUES ('Abi',  '1',  '21/01/2013','a')
INSERT INTO stud VALUES ('Abi',  '2',  '21/01/2013','p')
INSERT INTO stud VALUES ('bala',  '1',  '21/01/2013','p')
INSERT INTO stud VALUES ('bala',  '2',  '21/01/2013','a')
INSERT INTO stud VALUES ('bala',  '1',  '22/01/2013','od')
INSERT INTO stud VALUES ('bala',  '2',  '22/01/2013','ml')
INSERT INTO stud VALUES ('Abi',  '1',  '22/01/2013','ml')
INSERT INTO stud VALUES ('Abi',  '2',  '22/01/2013','od')

If i select this table i get the output as

SELECT * 
FROM   stud 
sname   hr            dt                att
Abi 1   2013-01-21 00:00:00.000  a
Abi 2   2013-01-21 00:00:00.000  p
bala    1   2013-01-21 00:00:00.000  p
bala    2   2013-01-21 00:00:00.000  a
bala    1   2013-01-22 00:00:00.000  od
bala    2   2013-01-22 00:00:00.000  ml
Abi 1   2013-01-22 00:00:00.000  ml
Abi 2   2013-01-22 00:00:00.000  od

but I want the output as follows in crystal report in ASP.NET ( Note : the date should given as dynamically as from_date to to to_date )

sname 21/01/2013 22/01/2013

I tried for this output from long days itself, but didn't get output.

4

1 回答 1

3

如果您使用的是 SQL Server 2005+,则可以通过多种方式应用该PIVOT功能。

您可以以静态数据透视表的形式对值进行硬编码:

select *
from
(
  select sname, 
    'hour_no_'+hr+'_'+convert(nvarchar(10), dt, 120) dt,
    att
  from stud
) st
pivot
(
  max(att)
  for dt in ([hour_no_1_2013-01-21], [hour_no_2_2013-01-21],
             [hour_no_1_2013-01-22], [hour_no_2_2013-01-22])
) piv

请参阅带有演示的 SQL Fiddle

或者您可以使用动态 sql 在运行时生成 sql 语句。查询的动态版本是:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX)

select @cols 
  = STUFF((SELECT ', ' + QUOTENAME('Hour_No_'+hr+'_'++convert(nvarchar(10), dt, 120)) 
           from stud
           group by hr, dt
           order by dt, hr
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT sname,' + @cols + ' from 
             (
                select sname, 
                  ''hour_no_''+hr+''_''+convert(nvarchar(10), dt, 120) dt,
                  att
                from stud
            ) x
            pivot 
            (
                max(att)
                for dt in (' + @cols + ')
            ) p '

execute(@query)

请参阅SQL Fiddle with Demo

两者都给出结果:

| SNAME | HOUR_NO_1_2013-01-21 | HOUR_NO_2_2013-01-21 | HOUR_NO_1_2013-01-22 | HOUR_NO_2_2013-01-22 |
-----------------------------------------------------------------------------------------------------
|   Abi |                    a |                    p |                   ml |                   od |
|  bala |                    p |                    a |                   od |                   ml |
于 2013-01-25T19:56:26.513 回答