如何在 UNION 之前进行 ORDER BY

How to ORDER BY before UNION

我有一个问题需要 UNION 2 tables.

第一个 table 实例用于 headers 个结果:

SELECT 'Department', 'ItemNumber', 'ProductDescription', 'Category', 'Group', 'SubGroup', 'Total Qty', 'Total Sales','07:00', '07:30' 

然后我在另一个 table 上 UNION 并且一切正常:

    UNION ALL 
SELECT i.STRDEPTCODE, CAST(i.LINTITEMNUMBER AS nvarchar), i.STRPRODUCTDESCRIPTION, i.STRCATCODE, i.STRGROUPCODE, i.STRSUBGROUPCODE, 

ISNULL((SELECT CAST(SUM(d.DBLQTYSOLD) AS nvarchar) FROM DAILYSALES d  WHERE d.STRSALETYPE = 'I' AND d.LINTITEMNUMBER = i.LINTITEMNUMBER AND d.DTMSALEDATETIME >= '2015-02-26 07:00:00' AND d.DTMSALEDATETIME < '2015-02-26 08:00:00' ), 0) AS 'Total Qty',  
ISNULL((SELECT CAST(SUM(d.CURSALES) AS nvarchar) FROM DAILYSALES d  WHERE d.STRSALETYPE = 'I' AND d.LINTITEMNUMBER = i.LINTITEMNUMBER AND d.DTMSALEDATETIME >= '2015-02-26 07:30:00' AND d.DTMSALEDATETIME < '2015-02-26 09:00:00' ), 0) AS 'Total Sales',
ISNULL((SELECT CAST(SUM(d.DBLQTYSOLD) AS nvarchar) FROM DAILYSALES d  WHERE d.STRSALETYPE = 'I' AND d.LINTITEMNUMBER = i.LINTITEMNUMBER AND d.DTMSALEDATETIME >= '2015-02-26 06:30:00' AND d.DTMSALEDATETIME < '2015-02-26 07:00:00' ), 0) AS '07:00',
ISNULL((SELECT CAST(SUM(d.DBLQTYSOLD) AS nvarchar) FROM DAILYSALES d  WHERE d.STRSALETYPE = 'I' AND d.LINTITEMNUMBER = i.LINTITEMNUMBER AND d.DTMSALEDATETIME >= '2015-02-26 07:00:00' AND d.DTMSALEDATETIME < '2015-02-26 07:30:00' ), 0) AS '07:30'

FROM ITEM i LEFT OUTER JOIN  (

    SELECT i.LINTITEMNUMBER, SUM(ds.DBLQTYSOLD) AS QTY, SUM(ds.CURSELLPRICE1) AS Value  
    FROM ITEM i LEFT JOIN DAILYSALES ds ON i.LINTITEMNUMBER=ds.LINTITEMNUMBER 
    WHERE ds.STRSALETYPE = 'I' AND ds.DTMSALEDATETIME >= '2015-02-26 07:00:00' AND ds.DTMSALEDATETIME < '2015-02-26 08:00:00' 

    GROUP BY i.STRDEPTCODE, i.LINTITEMNUMBER, i.STRPRODUCTDESCRIPTION, i.STRCATCODE, i.STRGROUPCODE, i.STRSUBGROUPCODE  ) t  
    on t.LINTITEMNUMBER= i.LINTITEMNUMBER WHERE t.QTY > 0 

问题是我需要按 LINTITEMNUMBER 进行排序(在将其解析为字符串之前),以便正确排序。

我必须在结果中包含 headers 而不是列 headers 因为接收程序不会处理 headers.

你不能在最后加上ORDER BY吗?像这样:

ORDER BY i.LINTITEMNUMBER

或者,如果这不起作用,请尝试将其转换回数字

ORDER BY CAST(i.LINTITEMNUMBER AS NUMERIC)

添加一个列,您可以使用该列按第一行具有 0 的位置或保证它排在第一位的内容进行排序。将联合查询放在派生的 table 中并仅提取您需要按引入的排序列排序的列。

您的查询有所简化。

select T.STRDEPTCODE,
       T.ITEMNUMBER,
       T.STRPRODUCTDESCRIPTION
from (
     select 0 as SortCol,
            'Department' as STRDEPTCODE,
            'ItemNumber' as ITEMNUMBER,
            'ProductDescription' as STRPRODUCTDESCRIPTION
     union all
     select T.LINTITEMNUMBER,
            T.STRDEPTCODE,
            cast(T.LINTITEMNUMBER as varchar(11)),
            T.STRPRODUCTDESCRIPTION
     from YourTable as T
     ) as T
order by T.SortCol