如何调整此T-SQL查询,以便它返回一个表而不是两个? :)

时间:2010-08-18 01:58:09

标签: sql sql-server tsql

SELECT patron_name, producer.fed_number, tax_number, average_tb_test
  FROM producer 
 INNER JOIN producer_details ON producer.federal_number = producer_details.federal_number
 INNER JOIN statement ON producer.patron_number = statement.patron_number
 WHERE producer.patron_number = @PatronNo
 (SELECT MAX(statement.statement_number), MAX(period_ending) FROM statement)

3 个答案:

答案 0 :(得分:2)

使用:

SELECT patron_name, 
       producer.fed_number, 
       tax_number, 
       average_tb_test,
       (SELECT MAX(s.statement_number) FROM STATEMENT s),
       (SELECT MAX(s.period_ending) FROM STATEMENT s),
   FROM PRODUCER
   JOIN producer_details ON producer.federal_number = producer_details.federal_number
   JOIN statement ON producer.patron_number = statement.patron_number
  WHERE producer.patron_number = @PatronNo

但是,每行会获得相同的最大STATEMENT.statement_numberSTATEMENT.period_ending值。这将为您提供每个patron_number值的最大值:

 SELECT patron_name, 
        producer.fed_number, 
        tax_number, 
        average_tb_test,
        x.max_statement_num,
        x.max_period
   FROM PRODUCER
   JOIN producer_details ON producer.federal_number = producer_details.federal_number
   JOIN STATEMENT ON producer.patron_number = statement.patron_number
   JOIN (SELECT s.patron_number,
                MAX(s.statement_number) AS max_statement_num,
                MAX(s.period_ending) AS max_period
           FROM STATEMENT s
       GROUP BY s.patron_number) x ON x.patron_number = producer.patron_number
  WHERE producer.patron_number = @PatronNo 

答案 1 :(得分:0)

我建议采用其中一种方法:

SELECT patron_name,  
       producer.fed_number,  
       tax_number,  
       average_tb_test, 
       MAX(statement.statement_number) as MaxStatementNumber,
       MAX(statement.period_ending) as MaxPeriodEnding
   FROM PRODUCER 
   JOIN producer_details ON producer.federal_number = producer_details.federal_number 
   JOIN statement ON producer.patron_number = statement.patron_number 
  WHERE producer.patron_number = @PatronNo 
  GROUP BY patron_name,  
       producer.fed_number,  
       tax_number,  
       average_tb_test

DECLARE @MaxStatementNumber INT, @MaxPeriodEnding INT
SELECT @MaxStatementNumber = MAX(statement.statement_number), @MaxPeriodEnding = MAX(period_ending) FROM statement

SELECT patron_name, producer.fed_number, tax_number, average_tb_test, @MaxStatementNumber AS maxStatementNumber, @MaxPeriodEnding AS MaxPeriodEnding 
  FROM producer  
 INNER JOIN producer_details ON producer.federal_number = producer_details.federal_number 
 INNER JOIN statement ON producer.patron_number = statement.patron_number 
 WHERE producer.patron_number = @PatronNo

这取决于您正在寻找的结果。如果你想要每组patron_name等的MaxStatemetnNumber和MaxEndingPeriod,请使用第一个,否则使用第二个。

答案 2 :(得分:-1)

T-SQL UNION运算符会将两个或多个查询合并为一个结果集。