我为每月的销售额创建了一个数据透视表,我想按当月对数据进行排序。我想知道是否可以使用 case 语句和 order by;我在下面试过这个(虽然不工作);
数据库服务器:SQL Server 2008
SELECT txt_web_name,
SUM(CASE WHEN MONTH(dte_pay_paydate) = 1 AND txt_pay_type <> 'Credit' THEN mon_pay_amount ELSE 0 END) AS 'January',
SUM(CASE WHEN MONTH(dte_pay_paydate) = 2 AND txt_pay_type <> 'Credit' THEN mon_pay_amount ELSE 0 END) AS 'February',
SUM(CASE WHEN MONTH(dte_pay_paydate) = 3 AND txt_pay_type <> 'Credit' THEN mon_pay_amount ELSE 0 END) AS 'March',
SUM(CASE WHEN MONTH(dte_pay_paydate) = 4 AND txt_pay_type <> 'Credit' THEN mon_pay_amount ELSE 0 END) AS 'April',
SUM(CASE WHEN MONTH(dte_pay_paydate) = 5 AND txt_pay_type <> 'Credit' THEN mon_pay_amount ELSE 0 END) AS 'May',
SUM(CASE WHEN MONTH(dte_pay_paydate) = 6 AND txt_pay_type <> 'Credit' THEN mon_pay_amount ELSE 0 END) AS 'June',
SUM(CASE WHEN MONTH(dte_pay_paydate) = 7 AND txt_pay_type <> 'Credit' THEN mon_pay_amount ELSE 0 END) AS 'July',
SUM(CASE WHEN MONTH(dte_pay_paydate) = 8 AND txt_pay_type <> 'Credit' THEN mon_pay_amount ELSE 0 END) AS 'August',
SUM(CASE WHEN MONTH(dte_pay_paydate) = 9 AND txt_pay_type <> 'Credit' THEN mon_pay_amount ELSE 0 END) AS 'September',
SUM(CASE WHEN MONTH(dte_pay_paydate) = 10 AND txt_pay_type <> 'Credit' THEN mon_pay_amount ELSE 0 END) AS 'October',
SUM(CASE WHEN MONTH(dte_pay_paydate) = 11 AND txt_pay_type <> 'Credit' THEN mon_pay_amount ELSE 0 END) AS 'November',
SUM(CASE WHEN MONTH(dte_pay_paydate) = 12 AND txt_pay_type <> 'Credit' THEN mon_pay_amount ELSE 0 END) AS 'December'
FROM tbl_payment
INNER JOIN dbo.tbl_orders ON (uid_pay_orderid = uid_orders)
INNER JOIN dbo.tbl_websites ON (uid_order_webid = uid_websites)
WHERE dbo.tbl_payment.bit_pay_paid = 1
GROUP BY txt_web_name
ORDER BY
CASE
WHEN MONTH(GETDATE()) = 1 THEN 'January'
WHEN MONTH(GETDATE()) = 2 THEN 'February'
WHEN MONTH(GETDATE()) = 3 THEN 'March'
WHEN MONTH(GETDATE()) = 4 THEN 'April'
WHEN MONTH(GETDATE()) = 5 THEN 'May'
WHEN MONTH(GETDATE()) = 6 THEN 'June'
WHEN MONTH(GETDATE()) = 7 THEN 'July'
WHEN MONTH(GETDATE()) = 8 THEN 'August'
WHEN MONTH(GETDATE()) = 9 THEN 'September'
WHEN MONTH(GETDATE()) = 10 THEN 'October'
WHEN MONTH(GETDATE()) = 11 THEN 'November'
WHEN MONTH(GETDATE()) = 12 THEN 'December'
END DESC