質問

I'm getting the following error messages:

Msg 8120, Level 16, State 1, Line 1 Column 'customers.member_category' is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause. Msg 104, Level 16, State 1, Line 1 ORDER BY items must appear in the select list if the statement contains a UNION, INTERSECT or EXCEPT operator.

How can I order the results by the case?

Thanks

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                                
役に立ちましたか?

解決

The second part of your UNION statement does not contain field member_category. This violates basic principle of UNION which is that number and order of columns in each statement should be same.

To resolve the issue, you need to add member_category both in the list of retrieved columns and in the GROUP BY clause.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top