如何使用UNION ALL语句修复此SQL?

时间:2019-02-01 07:50:57

标签: mysql sql

我有一个要根据名称汇总的每日数据列表,但按日期分组和显示。我想从Bookings表和POS中合并。我设法获得每个单独的预订和POS,但是在尝试合并时却失败了。

当我添加UNION ALL语句时,select语句很好,但是失败了

Select Name, CONVERT(char(10), DatePayment,120), SUM(Amount) Amount 
From (
select PT.Name, CONVERT(char(10), DatePayment, 120) Date, SUM(Amount) Amount    
    From Payments P 
        Inner Join PaymentTypes PT On P.PaymentType = PT.ID 
        Inner Join BookingPayments BP On P.ID = BP.PaymentID 
        Inner Join Bookings B On B.ID = BP.BookingID 
        Where   DatePayment >= '2018-12-01 00:00:00' And 
                DatePayment <= '2018-12-31 23:59:59.997' And 
                BookingStatus IN (0,2,3,4,6) 
        Group By PT.Name, CONVERT(char(10), DatePayment, 120)

UNION ALL
Select  PT.Name, CONVERT(char(10), DatePayment, 120) Date, SUM(P.Amount) Amount 
From Payments P 
        Inner Join PaymentTypes PT On P.PaymentType = PT.ID 
        Inner Join POSSales POS On P.ID = POS.PaymentID 
        Where   DatePayment >= '2018-12-01 00:00:00' And 
                DatePayment <= '2018-12-31 23:59:59.997' 
        Group By PT.Name, CONVERT(char(10), DatePayment, 120))

a Group By Name, CONVERT(char(10), DatePayment, 120)
order by CONVERT(char(10), DatePayment, 120);

我一直收到以下错误

Msg 207, Level 16, State 1, Line 22
Invalid column name 'DatePayment'.
Msg 207, Level 16, State 1, Line 1
Invalid column name 'DatePayment'.
Msg 207, Level 16, State 1, Line 23
Invalid column name 'DatePayment'.

1 个答案:

答案 0 :(得分:1)

您需要使用Date作为代替DatePayment的别名,而是使用别名来选择

   Select Name, CONVERT(char(10), `Date`,120), SUM(Amount) Amount 
        From (
        select PT.Name, CONVERT(char(10), DatePayment, 120) Date, SUM(Amount) Amount    
            From Payments P 
                Inner Join PaymentTypes PT On P.PaymentType = PT.ID 
                Inner Join BookingPayments BP On P.ID = BP.PaymentID 
                Inner Join Bookings B On B.ID = BP.BookingID 
                Where   DatePayment >= '2018-12-01 00:00:00' And 
                        DatePayment <= '2018-12-31 23:59:59.997' And 
                        BookingStatus IN (0,2,3,4,6) 
                Group By PT.Name, CONVERT(char(10), DatePayment, 120)

        UNION ALL
        Select  PT.Name, CONVERT(char(10), DatePayment, 120) Date, SUM(P.Amount) Amount 
        From Payments P 
                Inner Join PaymentTypes PT On P.PaymentType = PT.ID 
                Inner Join POSSales POS On P.ID = POS.PaymentID 
                Where   DatePayment >= '2018-12-01 00:00:00' And 
                        DatePayment <= '2018-12-31 23:59:59.997' 
                Group By PT.Name, CONVERT(char(10), DatePayment, 120)
)a Group By Name, CONVERT(char(10), `Date`, 120)
   order by CONVERT(char(10), `Date`, 120);