美好的一天我需要按Fecha
列排序,但在使用order by
时我不能,因为select
中的union
没有相同的列。你怎么能按这个字段排序Fecha
。你能帮我解决一下吗?
例如如下。
以下是我正在使用的查询。
SELECT 'PESO:','VOLUMEN:','NO. PIEZAS:','ETD:','ETA:'
UNION ALL
SELECT
(SELECT ISNULL(Valor,'') FROM MovCampoExtra WHERE Modulo = 'VTAS' AND ID = Venta.ID AND CampoExtra = 'CEDIS0103') AS pesoBruto,
(SELECT ISNULL(Valor,'') FROM MovCampoExtra WHERE Modulo = 'VTAS' AND ID = Venta.ID AND CampoExtra = 'CEDIS0121') AS volumen,
(SELECT ISNULL(Valor,'') FROM MovCampoExtra WHERE Modulo = 'VTAS' AND ID = Venta.ID AND CampoExtra = 'CEDIS0102') AS cantidadUnidades,
(SELECT CEDIS0120 FROM VentaCampoExtra WHERE ID = Venta.ID) AS ETD,
(SELECT CEDIS0123 FROM VentaCampoExtra WHERE ID = Venta.ID) AS ETA
FROM Venta
--Venta AS v
INNER JOIN Cte AS c ON c.Cliente = Venta.Cliente
INNER JOIN Usuario us On us.Usuario = Venta.Usuario
WHERE
@Origen=Venta.TMLICentroCosto AND
Venta.Mov IN ('Instruccion EXPO', 'Instruccion IMPO','Instruc. Nacional')
AND Venta.Empresa IN ('TM')
AND Venta.ID is NOT NULL
AND Venta.Estatus NOT IN ('Cancelado')
UNION ALL
SELECT 'FECHA:','HORA:','ACTIVIDADES:',' ',' '
UNION ALL
SELECT
Fecha = ISNULL(CONVERT(VARCHAR, mb.Fecha, 103),''), -- AS Fecha,
Hora = ISNULL(CONVERT(VARCHAR, mb.Fecha, 108),''), -- AS Hora,
Comentarios = ISNULL(mb.Evento2,''),
'',
''
FROM Venta
--Venta AS v
INNER JOIN Cte AS c ON c.Cliente = Venta.Cliente
LEFT OUTER JOIN MovBitacora AS mb ON mb.ID = Venta.ID
INNER JOIN Usuario us On us.Usuario = Venta.Usuario
WHERE
@Origen=Venta.TMLICentroCosto AND
Venta.Mov IN ('Instruccion EXPO', 'Instruccion IMPO','Instruc. Nacional')
AND Venta.Empresa IN ('TM')
AND Venta.ID is NOT NULL
AND Venta.Estatus NOT IN ('Cancelado')
ORDER BY Fecha ASC
RETURN
END
答案 0 :(得分:0)
好吧首先呻吟出来,这是一种可怕的做事方式。您不应该从sql查询返回标头列,并将两个不相关的查询混合在一起。这应该是应用程序层调用的两个查询,它们也应该处理标题。
但是如果你出于某种神秘的原因必须这样做,你可以添加一个"排序"每个查询的列
Header 1 sortval = A
Peso query sortval = B + Peso
Header 2 sortval = C
Fecha query sortval = D + Fecha (in YYYYMMDD format)
然后在整个事物中添加一个大的选择来选择列(您需要在第一个标题选择中添加别名)并按sortval排序。