如何在UNION之前订购

时间:2015-03-23 13:29:33

标签: sql sql-server subquery sql-order-by

我有一个问题,我需要UNION 2表。

第一个表格实例用于结果的标题:

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

然后我在另一张桌子上使用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(在解析为字符串之前)进行排序,以便正确排序。

我必须在结果中包含标题而不是列标题,因为接收程序不会处理标题。

2 个答案:

答案 0 :(得分:3)

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

您的查询有所简化。

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

答案 1 :(得分:0)

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

ORDER BY i.LINTITEMNUMBER

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

ORDER BY CAST(i.LINTITEMNUMBER AS NUMERIC)