在SQL server中使用内部联接联接3个表

本文关键字:内部 3个表 SQL server | 更新日期: 2023-09-27 18:20:01

我正在使用c#处理.NET 3.5中的winformssql server 2005

我需要使用内部联接来联接3个表,如Advance_costroom_no_infobill。。。

SELECT
      bill.bill_no AS BillNo
    , COUNT(room_no_info.room_number) AS TotalRoom
    , CONVERT(VARCHAR(11), room_no_info.in_date, 106) AS InDate
    , CONVERT(VARCHAR(11), room_no_info.out_date, 106) AS OutDate
    , bill.total AS Amount
    , Advance_cost.total_amount AS Advance
    , Advance_cost.total_amount AS Paid
    , bill.Balance AS Balance
FROM room_no_info
INNER JOIN bill ON bill.bill_no = room_no_info.bill_no
INNER JOIN Advance_cost ON bill.bill_no = Advance_cost.room_bill_no 
     AND bill.Date = '26-Jun-13'
GROUP BY
      bill.bill_no
    , room_no_info.in_date
    , room_no_info.out_date
    , bill.total
    , Advance_cost.total_amount
    , bill.Balance

在CCD_ 6中,表数据对于CCD_。所以join中的第三个条件为false,所以它不会显示一些数据,但当第三个表值为空时,我需要Advance_cost.total_amount=0

有什么想法吗?

在SQL server中使用内部联接联接3个表

尝试使用LEFT JOIN和ISNULL

SELECT
      bill.bill_no AS BillNo
    , COUNT(room_no_info.room_number) AS TotalRoom
    , CONVERT(VARCHAR(11), room_no_info.in_date, 106) AS InDate
    , CONVERT(VARCHAR(11), room_no_info.out_date, 106) AS OutDate
    , bill.total AS Amount
    , ISNULL(Advance_cost.total_amount, 0) AS Advance
    , ISNULL(Advance_cost.total_amount, 0) AS Paid
    , bill.Balance AS Balance
FROM room_no_info
INNER JOIN bill ON bill.bill_no = room_no_info.bill_no
LEFT JOIN Advance_cost ON bill.bill_no = Advance_cost.room_bill_no 
     AND bill.Date = '26-Jun-13'
GROUP BY
      bill.bill_no
    , room_no_info.in_date
    , room_no_info.out_date
    , bill.total
    , Advance_cost.total_amount
    , bill.Balance
SELECT
      bill.bill_no AS BillNo
    , COUNT(room_no_info.room_number) AS TotalRoom
    , CONVERT(VARCHAR(11), room_no_info.in_date, 106) AS InDate
    , CONVERT(VARCHAR(11), room_no_info.out_date, 106) AS OutDate
    , bill.total AS Amount
    , ISNULL(Advance_cost.total_amount, 0) AS Advance
    , ISNULL(Advance_cost.total_amount, 0) AS Paid
    , bill.Balance AS Balance
FROM room_no_info
INNER JOIN bill ON bill.bill_no = room_no_info.bill_no
LEFT OUTER JOIN Advance_cost ON bill.bill_no = Advance_cost.room_bill_no 
     AND bill.Date = '26-Jun-13'
GROUP BY
      bill.bill_no
    , room_no_info.in_date
    , room_no_info.out_date
    , bill.total
    , Advance_cost.total_amount
    , bill.Balance