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

时间:2013-06-27 07:07:56

标签: c# sql sql-server winforms

我正在使用.NET 3.5中的winforms和使用c#。

sql 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
advance_cost表数据中的

可能为空,或者没有bill.date日期的数据。因此,join中的第三个条件变为false,因此它不显示某些数据,但当第三个表值为空时我需要Advance_cost.total_amount=0

有什么想法吗?

2 个答案:

答案 0 :(得分:2)

尝试使用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

答案 1 :(得分:1)

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