加入和联合的声明不起作用?

时间:2018-02-01 14:16:06

标签: sql-server sql-server-2008

我在我的代码中使用where语句但是我没有得到正确的结果。

SELECT
            t1.HistoryID
            , t1.CustomerID
            , CONVERT(VARCHAR (5), t2.hour, 108)
            , t1.Text1
            , t1.Text2
            , t1.HistoryID2
            , t1.CustomerID2
            , t1.AppointmentDate
FROM
            AppointmentGrid t1
RIGHT JOIN  Gridhour        t2 ON t1.AppointmentHour = t2.Hour
UNION
SELECT
            t1.HistoryID
            , t1.CustomerID
            , CONVERT(VARCHAR (5), t1.AppointmentHour, 108)
            , t1.Text1
            , t1.Text2
            , t1.HistoryID2
            , t1.CustomerID2
            , t1.AppointmentDate
FROM
            AppointmentGrid t1
LEFT JOIN   Gridhour        t2 ON t1.AppointmentHour = t2.Hour
WHERE
            t1.AppointmentDate = '2018-03-21';

我不希望在我的示例中显示除此之外的任何其他日期。请看下面的图片。

MyImage

1 个答案:

答案 0 :(得分:0)

评论中提到的订单错误。 我猜你需要在问题中将SELECT包裹在派生表中并将ORDER BY放在外面

SELECT 
    X.*
FROM
(
    SELECT
                t1.HistoryID
                , t1.CustomerID
                , [Hour] = CONVERT(VARCHAR (5), t2.hour, 108)
                , t1.Text1
                , t1.Text2
                , t1.HistoryID2
                , t1.CustomerID2
                , t1.AppointmentDate
    FROM
                AppointmentGrid t1
    RIGHT JOIN  Gridhour        t2 ON t1.AppointmentHour = t2.Hour
    WHERE
                t1.AppointmentDate = '2018-03-21'
    UNION
    SELECT
                t1.HistoryID
                , t1.CustomerID
                , [Hour] = CONVERT(VARCHAR (5), t1.AppointmentHour, 108)
                , t1.Text1
                , t1.Text2
                , t1.HistoryID2
                , t1.CustomerID2
                , t1.AppointmentDate
    FROM
                AppointmentGrid t1
    LEFT JOIN   Gridhour        t2 ON t1.AppointmentHour = t2.Hour
    WHERE
                t1.AppointmentDate = '2018-03-21'
) X
ORDER BY X.whatever_column_you_want_to_order_by