请问SQL Server子查询帮助? (希望将现有的选择查询用作子查询)

时间:2012-02-07 00:50:35

标签: sql-server stored-procedures select

我有一个运行良好的存储过程,它是一个选择查询。我想使用当前查询作为子查询来更改通过一些聚合返回的内容。当前查询返回数据:

A  1/1/12
A  1/2/12
A  1/3/12
B  2/1/12
B  5/3/12
B  5/5/12

我希望将其视为:

A  1/1/12  1/3/12
B  2/1/12  5/5/12

所以我想要每个股票代码的日期值的分钟,然后是日期值的最大值。以下是我想要坚持的当前特色:

ALTER PROCEDURE dbo.sprocSymbsDatesForHistoricalPricingVol

AS

DECLARE @NxtAvailableDataDownloadDate date

SET @NxtAvailableDataDownloadDate = dbo.NextAvailableDataDownloadDate()

SELECT Symbol, TradingDate
FROM (SELECT tblSymbolsMain.Symbol, tblTradingDays.TradingDate
      FROM tblSymbolsMain CROSS JOIN
      tblTradingDays
      WHERE (tblTradingDays.TradingDate <= @NxtAvailableDataDownloadDate)) AS T1
      WHERE (NOT EXISTS
             (SELECT TradeDate, Symbol
              FROM tblDailyPricingAndVol
              WHERE (TradeDate = T1.TradingDate) AND (Symbol = T1.Symbol)))
ORDER BY Symbol, TradingDate

我尝试将选择查询包装为子查询不起作用...任何接受者?我相信这很简单。提前谢谢......

2 个答案:

答案 0 :(得分:2)

SELECT Symbol, MIN(TradingDate), Max(TradingDate)
FROM (
SELECT Symbol, TradingDate
FROM (SELECT tblSymbolsMain.Symbol, tblTradingDays.TradingDate
      FROM tblSymbolsMain CROSS JOIN
      tblTradingDays
      WHERE (tblTradingDays.TradingDate <= @NxtAvailableDataDownloadDate)) AS T1
      WHERE (NOT EXISTS
             (SELECT TradeDate, Symbol
              FROM tblDailyPricingAndVol
              WHERE (TradeDate = T1.TradingDate) AND (Symbol = T1.Symbol)))) t
GROUP BY Symbol

答案 1 :(得分:-2)

create table TestTab(symbol char(1), date datetime)


insert into TestTab values ('A','1/1/12')
insert into TestTab values('A','1/2/12')
insert into TestTab values('A','1/3/12')
insert into TestTab values('B','2/1/12')
insert into TestTab values('B','5/3/12')
insert into TestTab values('B','5/5/12')


select mi.symbol, mi.min_dt, ma.max_dt
from
(
    select symbol, min(date) min_dt
    from TestTab
    group by symbol
) mi full outer join
(

    select symbol, max(date) max_dt
    from TestTab
    group by symbol
) ma on (mi.symbol = ma.symbol)