SQL嵌套查询

时间:2009-11-28 22:56:08

标签: sql

有人可以帮助我在这张桌子上将以下查询串在一起..

CREATE TABLE [dbo].[TblNdx](
[ticker] [nvarchar](12) NOT NULL,
[date] [datetime] NULL,
[time] [datetime] NULL,
[open] [float] NULL,
[high] [float] NULL,
[low] [float] NULL,
[close] [float] NULL,
[volume] [float] NULL,
[change] [float] NULL
 ) ON [PRIMARY]

我需要一个查询来获取最后的xxx记录WHERE ...

SELECT ticker, date, time, [open], high, low, [close], volume, change
FROM   TblNdx 
WHERE  1=1
AND (ticker = '^IXIC') 
AND (date =
        (
            SELECT TOP (1) date as date1
            FROM TblNdx AS TblNdx_1
            WHERE (ticker = '^IXIC')
            ORDER BY date DESC
        )
    )
ORDER BY time DESC

然后将另一个列添加到计算机上一个关闭前一天的关闭... DATEDIFF(日期,日期,日期1)= 1和时间是从第二个上一天开始的前1个时间...换句话说,收盘价从前一天开始......嵌套的SELECT TOP 1条款正在杀死我......有人擅长这个吗?

我并不是说不尊重。我是一个像每个人一样喝玛格丽塔酒的极客......!无论如何,我感谢编辑。为了得到上一个最后的关闭日期,我试图修改..对这段代码的任何帮助都说'当子查询没有用EXISTS引入时,只能在SELECT列表中指定一个表达式。

我使用Visual Studio来运行查询,它缩进非常奇怪的方式......我想我真的不知道如何正确缩进!

SELECT ticker
    , date
    , time
    , [open]
    , high
    , low
    , [close]
    , volume
    , change
    , (SELECT TOP (1) time AS time1, [close] AS lastclose
         FROM TblNdx WHERE (DATEDIFF(day, date, date1) = 1) 
         AND (ticker = '^IXIC') ORDER BY time1 DESC) AS Expr1
    FROM TblNdx AS TblNdx_2
    WHERE (1 = 1) AND (ticker = '^IXIC') 
    AND (date = (SELECT TOP (1) date AS date1
                    FROM TblNdx AS TblNdx_1 
                    WHERE (ticker = '^IXIC')
                    ORDER BY date1 DESC))
    ORDER BY time DESC

2 个答案:

答案 0 :(得分:0)

     SELECT ticker
    , date
    , time
    , [open]
    , high
    , low
    , [close]
    , volume
    , change
    , (SELECT TOP (1) [close] FROM TblNdx AS t2
            WHERE (DATEDIFF(day, date, t1.date) = 2) 
                             AND (ticker = t1.ticker)
            ORDER BY time DESC) AS LastClose
    FROM TblNdx AS t1
    WHERE (ticker = '^IXIC')    
    AND (date = (SELECT TOP (1) date
        FROM TblNdx AS t3
                    WHERE (ticker = '^IXIC')
    ORDER BY time DESC))
    ORDER BY time DESC

我本来应该更清楚,我需要最后截止日期所有价格(收盘)最近的前1个日期...然后是前一个日期收盘价仅TOP 1次......

CS

答案 1 :(得分:0)

这是怎么回事?

注意:我没有测试,期待错别字

;WITH todaydate as
(
  SELECT max(date) as date, ticker
  FROM tblndx
  group by ticker
),  yesterdaydate as
(
  SELECT max(time) as time, ticker
  FROM tblndx
  group by ticker
  having  DATEDIFF(Day, date, getdate()) = 1
)
SELECT ticker
    , date
    , time
    , [open]
    , high
    , low
    , [close]
    , volume
    , change
    , yeserdaydate.time as [yeserday time]
from tblndx
inner join todaydate on tblndx.ticker = todaydate.ticker and tblndx.date = todaydate.date
left join yesterdaydate on tblndx.ticker = yeserdaydate.ticker