2009-11-28 332 views
-2

有人可以幫助我得到這個表串成以下查詢..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 

然後將另一個列添加到計算機LASTCLOSE,這是上一個日期的上一個關閉日期... DATEDIFF(日期,日期,date1)= 1並且時間是前一天的第一個時間...換句話說,前一天...嵌套的SELECT TOP 1子句正在殺死我......任何人都擅長這個?

我不是不尊重。我是一個像每個人一樣喝瑪格麗塔酒的極客......!無論如何,我欣賞編輯。爲了得到前一個最後關閉日期,我試圖修改..任何與此代碼的幫助它說'只有一個表達式可以在SELECT列表中指定當子查詢沒有與EXISTS引入..

我使用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 
+0

我們都會寧願去得到一些瑪格麗塔。 -1沒有表現出任何的尊重。 – 2009-11-28 23:23:27

+0

我有一種感覺,你會從正確縮進你的代碼中受益匪淺。 – 2009-11-28 23:26:34

+0

在SQL中大喊大叫,但文字大喊大叫。 – BalusC 2009-11-29 02:47:42

回答

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 
+0

夠好,謝謝... – CraigJSte 2009-12-02 13:31:03

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