在SQL查询中加入来自两个表的匹配结果

时间:2011-11-03 08:42:56

标签: sql-server-2008

我在SQL查询中遇到问题。

有两个表:

1:POrder包含列:

[Id] [int] IDENTITY(1,1) NOT NULL,
[PO_Date] [smalldatetime] NOT NULL,
[PO_No] [varchar](10) NOT NULL,
[Party_Id] [int] NOT NULL,
[Currency] [varchar](10) NOT NULL,
[Total_Value] [numeric](12, 2) NULL,
[Remarks] [varchar](250) NULL,
[PO_Status] [varchar](10) NULL,
[Y_CODE] [varchar](4) NULL,

2:Invoice列:

[Id] [int] IDENTITY(1,1) NOT NULL,
[Y_Code] [varchar](4) NULL,
[Inv_Date] [smalldatetime] NOT NULL,
[Inv_No] [varchar](10) NOT NULL,
[PO_No] [varchar](10) NOT NULL,
[Party_Id] [int] NOT NULL,
[Total_Value] [numeric](12, 2) NULL,
[Remarks] [varchar](250) NULL,
[Inv_Status] [varchar](10) NULL,
[Complete_Date] [smalldatetime] NULL,
[OPI_Date] [smalldatetime] NULL,
[Pmt_Status] [varchar](10) NULL,

对于POrder中的行,Invoice表中可能有多行。

我必须确定 - POrder中是否有一行 - Invoice中有任何行。 PO_No是两个表格中的共同列。

结果应该是:

PO_No   Billed
11      Yes (if row(s) found in invoice) 
12      No  (if no row found in invoice)

2 个答案:

答案 0 :(得分:2)

试试这个

SELECT po.PO_No,
    (SELECT COUNT(*) FROM Invoice
     WHERE PO_No = po.PO_No) AS Billed
FROM POrder po

答案 1 :(得分:1)

选项1(使用DISTINCT进行LEFT OUTER JOIN):

SELECT DISTINCT
p.PO_No,
(CASE WHEN i.PO_No IS NULL THEN 'No' ELSE 'Yes' END) AS Billed
FROM POrder p
LEFT OUTER JOIN Invoice i ON i.PO_No = p.PO_No
ORDER BY p.PO_No ASC

选项2(SUBSELECT):

SELECT
PO_No,
(CASE WHEN C > 0 THEN 'Yes' ELSE 'No' END) AS Billed
FROM
(
SELECT 
p.PO_No,
(SELECT COUNT(*) FROM Invoice i WHERE i.PO_No = p.PO_No) AS C
FROM POrder p
)
ORDER BY PO_No ASC