SQL Server 2008 - 错误按个案排序

时间:2014-03-21 01:14:37

标签: sql-server-2008 rollup

我收到以下错误消息:

Msg 8120,Level 16,State 1,Line 1 专栏' customers.member_category'在选择列表中无效,因为它不包含在聚合函数或GROUP BY子句中。 Msg 104,Level 16,State 1,Line 1 如果语句包含UNION,INTERSECT或EXCEPT运算符,则ORDER BY项必须出现在选择列表中。

如何通过案例订购结果?

由于

SELECT
Date,
order_id,
member_category,
COUNT(*) AS no_items, 
SUM(item_amount) AS total_amount
FROM 
order_items OI (NOLOCK) JOIN customers C (NOLOCK) 
ON OI.CUSTOMER_NO = C.CUSTOMER_NO
WHERE 
DATE = '01 FEB 2014'
GROUP BY 
order_id, 
member_category
UNION
SELECT
    '',
    '',
'Total',
COUNT(*) AS no_items, 
SUM(item_amount) AS total_amount
FROM 
order_items OI (NOLOCK) JOIN customers C (NOLOCK) 
ON OI.CUSTOMER_NO = C.CUSTOMER_NO
WHERE 
DATE = '01 FEB 2014'
GROUP BY Date WITH ROLLUP
ORDER BY Date ASC, CASE member_category WHEN 'VIP' THEN 1
                    WHEN 'STD' THEN 2                   
                    WHEN 'GLD' THEN 3 
           END                                

1 个答案:

答案 0 :(得分:0)

UNION语句的第二部分不包含字段member_category。这违反了UNION的基本原则,即每个语句中列的数量和顺序应该相同。

要解决此问题,您需要在检索到的列列表和member_category子句中添加GROUP BY