如何在SQL Server 2008中构建SQL子查询?

时间:2018-02-22 13:11:10

标签: sql sql-server sql-server-2008 subquery

我要求从表中提取总行数 - ci_periodicBillings仅适用于客户,他们拥有来自另一个表的特定日期范围的行 - ci_invoiceHeaders。我正在使用MS SQL Server 2008,通过ODBC连接。

我创建了一个子查询,但是只有当ci_periodicBillings的行总数为1时才会有效。我发现ci_periodicBillings的结果是否超过1,它会将所找到的行相乘符合ci_invoiceHeaders标准的行数。

如果在ci_invoiceHeaders中满足条件,我只想显示ci_periodicBillings中没有任何乘法的行。我确信有一个简单的解决方案,但我目前无法看到树上的木材。

还有一些其他表仅用于列表目的(即设施/客户等)

SQL就在这里:

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

SELECT     


     b.name,
      b.forename, 
      b.surname,


       a.client,
       cast(a.BILLSTART as DATE) as BILLSTART, 
       cast(a.ENDBILL as DATE) as ENDBILL,
       a.RATE



           FROM         ci_periodicBillings as a
           inner join 
           (select f.name,     
           c.surname,c.forename,ih.client,ih.invoiceDate      
           FROM ci_invoiceHeaders ih
           LEFT JOIN ci_invoiceDetails id ON ih.invoiceNo = id.id
           INNER JOIn cs_clients c ON ih.client = c.guid
           INNER JOIN cs_facilities f ON c.facility = f.guid
           group by f.name, c.surname, 
           c.forename, ih.client,     ih.invoiceDate)   
           as b
           on  a.client = b.client 
    WHERE b.invoiceDate between '2017-08-01' and '2018-01-31'
    order by a.client

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT  b.name, b.forename, b.surname, a.client,
       cast(a.BILLSTART AS DATE) AS BILLSTART, 
       cast(a.ENDBILL AS DATE) AS ENDBILL, a.RATE
FROM ci_periodicBillings AS a inner join 
           (SELECT f.name, c.surname,c.forename,ih.client,DATE(ih.invoiceDate) invoiceDate    
           FROM ci_invoiceHeaders ih
           LEFT JOIN ci_invoiceDetails id ON ih.invoiceNo = id.id
           INNER JOIn cs_clients c ON ih.client = c.guid
           INNER JOIN cs_facilities f ON c.facility = f.guid
           WHERE ih.invoiceDate BETWEEN '2017-08-01' AND '2018-01-31'
           GROUP BY f.name, c.surname,c.forename,ih.client,DATE(ih.invoiceDate)) AS b
ON a.client = b.client 
ORDER BY a.client;