2008-09-30 20 views

Respuesta

3

El ejemplo en http://jdixon.dotnetdevelopersjournal.com/pivot_table_data_in_sql_server_2000_and_2005.htm solo funciona si sabe de antemano cuáles son los valores de las filas. Por ejemplo, supongamos que tiene una entidad con atributos personalizados y los atributos personalizados se implementan como filas en una tabla secundaria, donde la tabla secundaria es básicamente pares variable/valor, y esos pares de variable/valor son configurables.

color red 
size big 
city Chicago 

Voy a describir una técnica que funciona. Lo he usado NO lo estoy promocionando, pero funciona.

Para pivotar los datos donde no se sabe cuáles pueden ser los valores por adelantado, cree una tabla temporal sobre la marcha sin columnas. Luego use un cursor para recorrer sus filas, emitiendo una "tabla alternativa" construida dinámicamente para cada variable, de modo que al final su tabla temporal tenga las columnas, el color, el tamaño, la ciudad.

Luego inserta una fila en su tabla temporal, la actualiza mediante otro cursor a través de la variable, pares de valores y luego la selecciona, generalmente unida a su entidad principal, haciendo que parezcan esos pares personalizados de variable/valor eran como columnas incorporadas en la entidad principal original.

+2

El enlace está roto :(. –

2

El método de cursor descrito es probablemente el menos parecido a SQL que se debe usar. Como se mencionó, SQL 2005 y en adelante tiene PIVOT, que funciona muy bien. Pero para versiones anteriores y servidores que no son MS SQL, el método Rozenshtein de "Optimización de Transact-SQL" (edición: agotado, pero disponible de Amazon: http://www.amazon.com/Optimizing-Transact-SQL-Advanced-Programming-Techniques/dp/0964981203), es excelente para pivotar y desvirtuar datos. Utiliza características de puntos para convertir los datos basados ​​en filas en columnas. Rozenshtein describe varios casos, aquí está un ejemplo:

SELECT 
    RowValueNowAColumn = 
     CONVERT(varchar, 
      MAX(
      SUBSTRING(myTable.MyVarCharColumn,1,DATALENGTH(myTable.MyVarCharColumn) 
     * CHARINDEX(sa.SearchAttributeName,'MyRowValue')))) 
FROM 
    myTable 

Este método es mucho más eficiente que el uso de declaraciones de casos y trabaja para una variedad de tipos de datos e implementaciones de SQL (no sólo MS SQL).

1

mejor limitar a pequeña escala para este tipo de cosas. Sin embargo, si está utilizando SQL 2k y no tiene funciones PIVOT disponibles, he elaborado un proceso almacenado que debería hacer el trabajo por usted. Un poco de un trabajo de apuros, así que deshazte tanto como quieras. Pegue el siguiente en una ventana sql y edite el EXEC en la parte inferior como prefiera.Si quieres ver lo que se está generando, retire los -S en el medio:

IF EXISTS (SELECT * FROM SYSOBJECTS WHERE XTYPE = 'P' AND NAME = 'USP_LIST_CONCAT') 
DROP PROCEDURE USP_LIST_CONCAT 
GO 

CREATE PROCEDURE USP_LIST_CONCAT (@SourceTable NVARCHAR(1000) = '' ,@SplitColumn NVARCHAR(1000) = '' , @Deli NVARCHAR(10) = '', @KeyColumns NVARCHAR(2000) = '' , @Condition NVARCHAR(1000) = '') 
AS 
BEGIN 
SET NOCOUNT ON 

/* PROCEDURE CREATED 2010 FOR SQL SERVER 2000. SIMON HUGHES. */ 
/* NOTES: REMOVE --'s BELOW TO LIST GENERATED SQL. */ 

IF @SourceTable = '' OR @SourceTable = '?' OR @SourceTable = '/?' OR @SplitColumn = '' OR @KeyColumns = '' 
BEGIN 
PRINT 'Format for use:' 
PRINT ' USP_LIST_CONCAT ''SourceTable'', ''SplitColumn'', ''Deli'', ''KeyColumn1,...'', ''Column1 = 12345 AND ...''' 
PRINT '' 
PRINT 'Description:' 
PRINT 'The SourceTable should contain a number of records acting as a list of values.' 
PRINT 'The SplitColumn should be the name of the column holding the values wanted.' 
PRINT 'The Delimiter may be any single character or string ie ''/''' 
PRINT 'The KeyColumn may contain a comma separated list of columns that will be returned before the concatenated list.' 
PRINT 'The optional Conditions may be left blank or may include the following as examples:' 
PRINT ' ''Column1 = 12334 AND (Column2 = ''ABC'' OR Column3 = ''DEF'')''' 
PRINT '' 
PRINT 'A standard list in the format:' 
PRINT ' Store1, Employee1, Rabbits' 
PRINT ' Store1, Employee1, Dogs' 
PRINT ' Store1, Employee1, Cats' 
PRINT ' Store1, Employee2, Dogs' 
PRINT '' 
PRINT 'Will be returned as:' 
PRINT ' Store1, Employee1, Cats/Dogs/Rabbits' 
PRINT ' Store1, Employee2, Dogs' 
PRINT '' 
PRINT 'A full ORDER BY and DISTINCT is included' 
RETURN -1 
END 


DECLARE @SQLStatement NVARCHAR(4000) 

SELECT @SQLStatement = ' 
DECLARE @DynamicSQLStatement NVARCHAR(4000) 

SELECT @DynamicSQLStatement = ''SELECT '[email protected]+', SUBSTRING('' 

SELECT @DynamicSQLStatement = @DynamicSQLStatement + '' + '' + CHAR(10) + 
'' MAX(CASE WHEN '[email protected]+' = ''''''+RTRIM('[email protected]+')+'''''' THEN '''''[email protected]+'''+RTRIM('[email protected]+')+'''''' ELSE '''''''' END)'' 
FROM '+ @SourceTable +' ORDER BY '[email protected]+' 

SELECT @DynamicSQLStatement = @DynamicSQLStatement + '' ,2,7999) List'' + CHAR(10) + ''FROM '+ @SourceTable+''' + CHAR(10) +'''+CASE WHEN @Condition = '' THEN '/* WHERE */' ELSE 'WHERE '[email protected] END+ '''+ CHAR(10) + ''GROUP BY '[email protected]+''' 

SELECT @DynamicSQLStatement = REPLACE(@DynamicSQLStatement,''(+'',''('') 

-- SELECT @DynamicSQLStatement -- DEBUG ONLY 
EXEC (@DynamicSQLStatement)' 

EXEC (@SQLStatement) 

END 
GO 

EXEC USP_LIST_CONCAT 'MyTableName', 'ColumnForListing', 'Delimiter', 'KeyCol1, KeyCol2', 'Column1 = 123456' 
0

tengo datos en el formato siguiente

Survey_question_ID

correo electrónico (Usuario)

Respuesta

durante 1 encuesta hay 13 preguntas y respuestas la salida deseada que quería era

usuario --- --- Survey_question_ID1Survey_question_ID2

correo electrónico --- responde - - respuesta ........ así sucesivamente

Aquí está la solución para SQL Server 2000, el tipo de datos de campo Causa es TEXTO.

DROP TABLE #tmp 

DECLARE @tmpTable TABLE 
(
emailno NUMERIC, 
question1 VARCHAR(80), 
question2 VARCHAR(80), 
question3 VARCHAR(80), 
question4 VARCHAR(80), 
question5 VARCHAR(80), 
question6 VARCHAR(80), 
question7 VARCHAR(80), 
question8 VARCHAR(80), 
question9 VARCHAR(80), 
question10 VARCHAR(80), 
question11 VARCHAR(80), 
question12 VARCHAR(80), 
question13 VARCHAR(8000) 
) 

DECLARE @tmpTable2 TABLE 
(
emailNumber NUMERIC 
) 

DECLARE @counter INT 
DECLARE @Email INT 

SELECT @counter =COUNT(DISTINCT ans.email) FROM answers ans WHERE ans.surveyname=100430 AND ans.qnpkey BETWEEN 233702 AND 233714 
SELECT * INTO #tmp FROM @tmpTable 
INSERT INTO @tmpTable2 (emailNumber) SELECT DISTINCT CAST(ans.email AS NUMERIC) FROM answers ans WHERE ans.surveyname=100430 AND ans.qnpkey BETWEEN 233702 AND 233714 

WHILE @counter >0 

BEGIN 

     SELECT TOP 1 @Email= emailNumber FROM @tmpTable2 
     INSERT INTO @tmpTable (emailno) VALUES (@Email) 


     Update @tmpTable set question1=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233702 and [email protected] 
     Update @tmpTable set question2=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233703 and [email protected] 
     Update @tmpTable set question3=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233704 and [email protected] 
     Update @tmpTable set question4=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233705 and [email protected] 
     Update @tmpTable set question5=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233706 and [email protected] 
     Update @tmpTable set question6=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233707 and [email protected] 
     Update @tmpTable set question7=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233708 and [email protected] 
     Update @tmpTable set question8=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233709 and [email protected] 
     Update @tmpTable set question9=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233710 and [email protected] 
     Update @tmpTable set question10=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233711 and [email protected] 
     Update @tmpTable set question11=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233712 and [email protected] 
     Update @tmpTable set question12=CAST(answer as VARCHAR(80)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233713 and [email protected] 
     Update @tmpTable set question13=CAST(answer as VARCHAR(8000)) from answers ans where ans.surveyname=100430 and ans.qnpkey = 233714 and [email protected] 

     insert into #tmp select * from @tmpTable  

     DELETE FROM @tmpTable  
     DELETE FROM @tmpTable2 WHERE emailNumber= @Email 

     set @counter [email protected] -1 

End 

select * from #tmp 
Cuestiones relacionadas