Foros del Web » Programación para mayores de 30 ;) » Bases de Datos General » SQL Server »

Query cruzada

Estas en el tema de Query cruzada en el foro de SQL Server en Foros del Web. Buenos días a todos. Como puedo hacer una query para que en los campos de columna me aparezcan los valores de un campo. Por ejemplo ...
  #1 (permalink)  
Antiguo 05/09/2011, 05:03
 
Fecha de Ingreso: agosto-2008
Mensajes: 56
Antigüedad: 15 años, 8 meses
Puntos: 1
Query cruzada

Buenos días a todos.

Como puedo hacer una query para que en los campos de columna me aparezcan los valores de un campo.
Por ejemplo yo tengo un campo fecha, un campo nombrehotel y campo sensor y campo energía, yo quiero que en la query me aparezca:
fecha nombre hotel sensor1 sensor2 sensor3 sensor4
ens-------- ---------------- ---------- ----------- ----------- ----------
valor1 hotel columbus 10 50 10
valor2 hotel columbus 20 60
valor3 hotel x 30 70
''''''
'''''
valorn

Ahora mi query es la siguiente:
SELECT PointValue.PointID, Lans.LanId, Outstations.Thelabel, PointValue.DataTime, PointValue.DataValue, StrategyList.theLabel
FROM Lans INNER JOIN
Outstations ON Lans.lanID = Outstations.lanID INNER JOIN
StrategyList ON Outstations.outstationID = StrategyList.outstationID INNER JOIN
PointValue ON StrategyList.theIndex = PointValue.PointID INNER JOIN
SiteDetails ON Lans.siteID = SiteDetails.siteID
WHERE (Lans.LanNo = 20) AND (Outstations.NodeAddress= 20) AND (PointValue.DataTime >= '2011-06-17 04:00:00.000') AND (PointValue.DataTime <='2011-06-17 05:15:00.000')
  #2 (permalink)  
Antiguo 06/09/2011, 07:54
Avatar de Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Query cruzada

Revisa la funcion Pivot

Saludos!
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me
  #3 (permalink)  
Antiguo 06/09/2011, 09:41
 
Fecha de Ingreso: agosto-2008
Mensajes: 56
Antigüedad: 15 años, 8 meses
Puntos: 1
Respuesta: Query cruzada

ok, buscare información de pivot.

Muchas gracias.

Un saludo.
  #4 (permalink)  
Antiguo 06/09/2011, 12:24
Avatar de iislas
Colaborador
 
Fecha de Ingreso: julio-2007
Ubicación: Mexico, D.F.
Mensajes: 6.482
Antigüedad: 16 años, 9 meses
Puntos: 180
Respuesta: Query cruzada

Claro esta, que si tu version es 2005 o superior
__________________
MCTS Isaias Islas
  #5 (permalink)  
Antiguo 07/09/2011, 05:10
 
Fecha de Ingreso: agosto-2008
Mensajes: 56
Antigüedad: 15 años, 8 meses
Puntos: 1
Respuesta: Query cruzada

No me reconoce la función PIVOT, haciendo la query desde sql server management studio express
  #6 (permalink)  
Antiguo 07/09/2011, 05:12
 
Fecha de Ingreso: agosto-2008
Mensajes: 56
Antigüedad: 15 años, 8 meses
Puntos: 1
Respuesta: Query cruzada

SELECT Outstations.Thelabel, PointValue.DataTime, PointValue.DataValue, StrategyList.theLabel
FROM Lans INNER JOIN
Outstations ON Lans.lanID = Outstations.lanID INNER JOIN
StrategyList ON Outstations.outstationID = StrategyList.outstationID INNER JOIN
PointValue ON StrategyList.theIndex = PointValue.PointID INNER JOIN
SiteDetails ON Lans.siteID = SiteDetails.siteID
WHERE (Lans.LanNo = 20) AND (Outstations.NodeAddress= 20) AND (Outstations.Thelabel= 'Hotel Columbus') AND (PointValue.DataTime >= '2011-08-01 00:00:00.000') AND (PointValue.DataTime <='2011-08-31 23:45:00.000')

Quiero que los valores de strategyList.theLabel me aparezcan como columnas y la función pivot no me la coge.
  #7 (permalink)  
Antiguo 07/09/2011, 15:18
Avatar de iislas
Colaborador
 
Fecha de Ingreso: julio-2007
Ubicación: Mexico, D.F.
Mensajes: 6.482
Antigüedad: 16 años, 9 meses
Puntos: 180
Respuesta: Query cruzada

¿Version 2005 o superior?
__________________
MCTS Isaias Islas
  #8 (permalink)  
Antiguo 13/09/2011, 07:27
 
Fecha de Ingreso: agosto-2008
Mensajes: 56
Antigüedad: 15 años, 8 meses
Puntos: 1
Respuesta: Query cruzada

Versión 2005
  #9 (permalink)  
Antiguo 13/09/2011, 07:44
Avatar de Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Query cruzada

como estas usando la funcion pivot??
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me
  #10 (permalink)  
Antiguo 13/09/2011, 08:55
 
Fecha de Ingreso: agosto-2008
Mensajes: 56
Antigüedad: 15 años, 8 meses
Puntos: 1
Respuesta: Query cruzada

La estoy usando al final de la query pongo pivot y los campos que quiero me aparezcan sus valores como columnas.
  #11 (permalink)  
Antiguo 13/09/2011, 09:27
Avatar de Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Query cruzada

por eso pon el ejemplo de como lo estas usando(query)
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me
  #12 (permalink)  
Antiguo 22/09/2011, 07:57
 
Fecha de Ingreso: agosto-2008
Mensajes: 56
Antigüedad: 15 años, 8 meses
Puntos: 1
Respuesta: Query cruzada

la estoy usando así:
TRANSFORM Sum(Query.[DataValue]) AS SumaDeDataValue
SELECT Query.[dbo_Outstations].[theLabel], Query.[DataTime]
FROM Query
GROUP BY Query.[dbo_Outstations].[theLabel], Query.[DataTime]
PIVOT Query.[dbo_StrategyList].[theLabel]

En Access si funciona y ahora he creado un proyecto de access y ahí no me funciona??

Es sql express edition 2005.
  #13 (permalink)  
Antiguo 22/09/2011, 09:38
Avatar de Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Query cruzada

ya revisaste esta liga?

http://msdn.microsoft.com/en-us/library/ms177410.aspx

Saludos!
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me
  #14 (permalink)  
Antiguo 22/09/2011, 09:44
 
Fecha de Ingreso: agosto-2008
Mensajes: 56
Antigüedad: 15 años, 8 meses
Puntos: 1
Respuesta: Query cruzada

Si la he revisado pero no me funciona.

La función transform en sql no funciona, pero como pone en esa liga, tampoco me funciona.
Que puede ocurrir??
  #15 (permalink)  
Antiguo 22/09/2011, 10:02
Avatar de Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Query cruzada

Probe esta funcion en sql express 2005:

Código SQL:
Ver original
  1. --Create the table and insert values as portrayed in the previous example.
  2. DROP TABLE #pvt
  3. CREATE TABLE #pvt (VendorID INT, Emp1 INT, Emp2 INT,
  4.     Emp3 INT, Emp4 INT, Emp5 INT);
  5. GO
  6. INSERT INTO #pvt VALUES (1,4,3,5,4,4);
  7. INSERT INTO #pvt VALUES (2,4,1,5,5,5);
  8. INSERT INTO #pvt VALUES (3,4,3,5,4,4);
  9. INSERT INTO #pvt VALUES (4,4,2,5,5,4);
  10. INSERT INTO #pvt VALUES (5,5,1,5,5,5);
  11. GO
  12. --Unpivot the table.
  13. SELECT VendorID, Employee, Orders
  14. FROM
  15.    (SELECT VendorID, Emp1, Emp2, Emp3, Emp4, Emp5
  16.    FROM #pvt) p
  17. UNPIVOT
  18.    (Orders FOR Employee IN
  19.       (Emp1, Emp2, Emp3, Emp4, Emp5)
  20. )AS unpvt;

Y si funciona, a ver un ejemplo de tus datos para ayudarte
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me
  #16 (permalink)  
Antiguo 22/09/2011, 10:22
 
Fecha de Ingreso: agosto-2008
Mensajes: 56
Antigüedad: 15 años, 8 meses
Puntos: 1
Respuesta: Query cruzada

Yo tengo la query creada ya con los datos que quiero sacar, lo que quiero es que me los muestre cruzados.
No me hace falta crear la tabla, ni meterle valores quiero hacerlo a partir de la query.
Esta es la query inicial:
SELECT dbo.PointValue.PointID, dbo.Lans.lanID, dbo.Outstations.theLabel, dbo.PointValue.DataTime, dbo.PointValue.DataValue, dbo.StrategyList.theUnits,
dbo.StrategyList.theLabel AS Expr1
FROM dbo.Lans INNER JOIN
dbo.Outstations ON dbo.Lans.lanID = dbo.Outstations.lanID INNER JOIN
dbo.StrategyList ON dbo.Outstations.outstationID = dbo.StrategyList.outstationID INNER JOIN
dbo.PointValue ON dbo.StrategyList.theIndex = dbo.PointValue.PointID INNER JOIN
dbo.SiteDetails ON dbo.Lans.siteID = dbo.SiteDetails.siteID
WHERE (dbo.Lans.LanNo = 20) AND (dbo.Outstations.NodeAddress = 20)

PointID lanID theLabel DataTime DataValue theUnits Expr1
580 8 Hotel Columbus 10/07/2011 11:00 49,21 DegC TEP01

Y lo que quiero es que me ponga como columnas los campos de Expr1 (TEPO1 TEP02 TEP03)
  #17 (permalink)  
Antiguo 22/09/2011, 11:20
Avatar de Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Query cruzada

Código SQL:
Ver original
  1. CREATE TABLE #temp
  2. (
  3. pointid INT,
  4. lanid INT,
  5. thelabel VARCHAR(30),
  6. datatime datetime,
  7. datavalue VARCHAR(10),
  8. theunits VARCHAR(10),
  9. Expr1 VARCHAR(10)
  10. )
  11.  
  12.  
  13.  
  14. INSERT INTO #temp VALUES (580,8,'Hotel Columbus','10/07/2011 11:00','49,21','DegC','TEP01')
  15. INSERT INTO #temp VALUES (581,9,'Hotel Columbus2','10/08/2011 11:00','49,21','DegC2','TEP02')
  16. INSERT INTO #temp VALUES (581,9,'Hotel Columbus3','10/08/2011 11:00','49,21','DegC2','TEP03')
  17.  
  18.  
  19. SELECT pointid,lanid,thelabel,datatime,datavalue,theunits,[TEP01],[TEP02],[TEP03]
  20. FROM
  21. (
  22.    SELECT Expr1,pointid,lanid,thelabel,datatime,datavalue,theunits FROM #temp
  23. ) AS SOURCE
  24. pivot
  25. (
  26.   MAX(Expr1) FOR Expr1 IN ([TEP01],[TEP02],[TEP03])
  27. ) AS pvt

Resultado:


pointid lanid thelabel datatime datavalue theunits TEP01 TEP02 TEP03
580 8 Hotel Columbus 2011-10-07 11:00:00.000 49,21 DegC TEP01 NULL NULL
581 9 Hotel Columbus2 2011-10-08 11:00:00.000 49,21 DegC2 NULL TEP02 NULL
581 9 Hotel Columbus3 2011-10-08 11:00:00.000 49,21 DegC2 NULL NULL TEP03


Saludos!
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me
  #18 (permalink)  
Antiguo 22/09/2011, 15:56
Avatar de iislas
Colaborador
 
Fecha de Ingreso: julio-2007
Ubicación: Mexico, D.F.
Mensajes: 6.482
Antigüedad: 16 años, 9 meses
Puntos: 180
Respuesta: Query cruzada

Libras, mis respetos por su cordura, temple, paciencia y ganas de ayudar.
__________________
MCTS Isaias Islas
  #19 (permalink)  
Antiguo 22/09/2011, 16:03
Avatar de Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Query cruzada

Cita:
Iniciado por iislas Ver Mensaje
Libras, mis respetos por su cordura, temple, paciencia y ganas de ayudar.
Muchas Gracias iislas, mas que ganas de ayudar son ganas de aprender cosas nuevas(como esto del pivot que solo habia visto teoricamente) y porque no compartir lo poco o mucho que tengo de conocimientos :)
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me
  #20 (permalink)  
Antiguo 23/09/2011, 01:13
 
Fecha de Ingreso: agosto-2008
Mensajes: 56
Antigüedad: 15 años, 8 meses
Puntos: 1
Respuesta: Query cruzada

Muchas gracias Libras por toda tu ayuda.

Yo los valores que tu pones en el primer select de tep01, tep02, esos valores los tengo en el campo Expr1, y quiero que me los muestre en columnas. No creo que tenga que escribir en el select todos los valores a mano no??

Un saludo y de nuevo gracias.
  #21 (permalink)  
Antiguo 23/09/2011, 07:31
Avatar de Libras
Colaborador
 
Fecha de Ingreso: agosto-2006
Ubicación: En la hermosa perla de occidente
Mensajes: 7.412
Antigüedad: 17 años, 8 meses
Puntos: 774
Respuesta: Query cruzada

Yo los valores que tu pones en el primer select de tep01, tep02, esos valores los tengo en el campo Expr1

Pues esos valores los saque del campo expr1

pivot
(
max(Expr1) FOR Expr1 IN ([TEP01],[TEP02],[TEP03])
) AS pvt


nada mas que tienes que especificar que columnas y que valores son los que necesitas que te ponga en una tabla pivote, probaste el query???

Saludos!
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me

Etiquetas: fecha, query, select, campos
Atención: Estás leyendo un tema que no tiene actividad desde hace más de 6 MESES, te recomendamos abrir un Nuevo tema en lugar de responder al actual.
Respuesta

SíEste tema le ha gustado a 1 personas




La zona horaria es GMT -6. Ahora son las 01:18.