Ver Mensaje Individual
  #11 (permalink)  
Antiguo 25/09/2014, 15:06
Avatar de Libras
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: Group by con select *

Código SQL:
Ver original
  1. CREATE TABLE #temp
  2.  (
  3.  IdPedido INT IDENTITY (1,1),
  4.  Fecha datetime,
  5.  Importe INT,
  6.  estadoPedido INT,
  7.  idoficina INT)
  8.  
  9.  INSERT INTO #temp VALUES (getdate(),200,1,1)
  10.  INSERT INTO #temp VALUES (getdate(),100,1,1)
  11.  INSERT INTO #temp VALUES (getdate(),200,1,1)
  12.  INSERT INTO #temp VALUES (getdate(),200,2,1)
  13.  INSERT INTO #temp VALUES (getdate(),200,2,1)
  14.  INSERT INTO #temp VALUES (getdate(),200,1,2)
  15.  INSERT INTO #temp VALUES (getdate(),200,1,2)
  16.  
  17.  
  18.  CREATE TABLE #temp2
  19.  (
  20.  IdEstado INT,
  21.  Descripcion VARCHAR(200))
  22.  
  23.  INSERT INTO #temp2 VALUES (1,'Abierto')
  24.  INSERT INTO #temp2 VALUES (2,'Cerrado')
  25.  
  26.  CREATE TABLE #temp3
  27.  (
  28.  idoficina INT,
  29.  nombre VARCHAR(20)
  30.  )
  31.  
  32.  INSERT INTO #temp3 VALUES (1,'Oficina 1')
  33.  INSERT INTO #temp3 VALUES (2,'Oficina 2')
  34.  
  35.  SELECT DISTINCT t2.Descripcion,t4.total,t4.pedido,t4.fecha,t3.idoficina FROM #temp AS t1
  36.  LEFT JOIN #temp2 AS t2 ON (t1.estadoPedido=t2.IdEstado)
  37.  LEFT JOIN #temp3 AS t3 ON (t1.idoficina=t3.idoficina)
  38.  LEFT JOIN(
  39.  SELECT COUNT(estadopedido) AS total,idestado,MAX(fecha) AS fecha,MAX(IdPedido) AS pedido  FROM #temp AS t1
  40.  LEFT JOIN #temp2 AS t2 ON (t1.estadoPedido=t2.IdEstado)
  41.  LEFT JOIN #temp3 AS t3 ON (t1.idoficina=t3.idoficina)
  42.  GROUP BY estadoPedido,IdEstado) AS t4 ON (t1.estadoPedido=t4.IdEstado AND t1.Fecha=t4.fecha AND t1.IdPedido=t4.pedido)
  43.  WHERE t4.IdEstado IS NOT NULL

Descripcion total pedido fecha idoficina
Abierto 5 7 2014-09-25 15:36:53.643 2
Cerrado 2 5 2014-09-25 15:36:53.643 1


Aclarando, el id_pedido se tiene que filtrar o sacar el maximo, no puedes contar todos los registros de un estado y presentar todos los pedidos, otra cosa quien te dijo que los deadlocks son por subquerys?? sabes que es un subquery???
__________________
What does an execution plan say to t-sql query? Go f**k yourself, if you are not happy with me