开发者社区> 问答> 正文

SQL Server 2005从表1和表2选择数据,但如果表2的column1值为空,则从表3选择数

我的查询是

SELECT TblPharmacyBillingDetails.UPBNo, TblMasterBillingData.IPDNo, InPatRegistration.PatTitle+PatientName, TblPharmacyBillingDetails.InvoiceNo, TblPharmacyBillingDetails.InvoiceDateTime, TblPharmacyBillingDetails.BillingAmount
FROM TblPharmacyBillingDetails
INNER JOIN TblMasterBillingData ON TblPharmacyBillingDetails.UPBNo = TblMasterBillingData.UPBNo
INNER JOIN InPatRegistration ON TblMasterBillingData.IPDNo = InPatRegistration.IPDNo

但是如果TblMasterBillingData.IPDNo值是NULL select Data From TblMasterBillingData.OPDNo和

INNER JOIN OutPatRegistration ON TblMasterBillingData.OPDNo = OutPatRegistration.IPDNo

展开
收起
祖安文状元 2020-01-05 14:14:24 466 0
1 条回答
写回答
取消 提交回答
  • 您可以在演示查询中编写case statement或编写ISNULL()如下所示的函数。

    SELECT 
        Orders.OrderID, 
        Case when Customers1.CustomerName is null then Customers2.CustomerName else Customers1.CustomerName
            end as CustomerName, --way 1
        ISNULL(Customers1.CustomerName, Customers2.CustomerName) as Customer, --way 2
        Orders.OrderDate
    FROM Orders
    INNER JOIN Customers1 ON Orders.CustomerID = Customers1.CustomerID
    INNER JOIN Customers2 ON Orders.CustomerID = Customers2.CustomerID
    -- where your condition here
    -- order by your column name
    
    

    您还可以检查表中是否有数据,并使用if exists如下所示相应地联接表。

    if exists(select 1 from tablename where columnname = <your values>)
    
    2020-01-05 14:14:41
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
SQL Server在电子商务中的应用与实践 立即下载
GeoMesa on Spark SQL 立即下载
原生SQL on Hadoop引擎- Apache HAWQ 2.x最新技术解密malili 立即下载