2011-02-06 57 views
1

我的家人有幾個股票賬戶,我爲他們的內容保留一個股票價值表,每天輸入當前值。字段是...像我這樣的業餘愛好者面臨的SQL問題

ACCOUNT/TICKER/QUANTITY/CLOSINGDATE/ CLOSING (current price) 

要獲取當前股票內容和最近的價格的報告,我正在使用此代碼。我逐行添加,並獲得一個賬戶總額(例如賬戶#2)。桌子也是這樣設計的,所以我可以跟蹤個人股票表現。

SELECT distinct ticker, account, closingdate, quantity, closing, (quantity*closing) as "Net" 
FROM "stock values" AS S 
WHERE 
(account=2) and 
(quantity>0.000001) and 
(closingdate =(SELECT MAX(closingdate) FROM "stock values" WHERE (ticker = S.ticker) and (account=s.account))) 

但現在我想做的是創造一個報告,看起來像這樣在TDBGrid中,這樣......我得到的報告,通過賬戶與最近的獨特行情分組加起來爲該帳戶。四天後,我無法解決這個問題。

Account     Value 
     1     35,000.00 
     2     122,132,32 
     3      43.23 

我使用的Nexus 3德爾福7

任何幫助,大大不勝感激。

拉里

回答

1

對我來說,它看起來像你只需要添加一個group by

select account 
,  sum(quantity*closing) 
from "stock_values" as S 
where s.closingdate = 
     (
     select max(closingdate) 
     from "stock values" as S2 
     where S2.ticker = S.ticker 
       and S2.account = S1.account 
     ) 
group by 
     account 
1

既然你可以擁有多個賬戶的股票一樣,我會預先查詢的最後截止日期每種股票的每個股票...這樣,如果您有公司「X」的股票並且輸入了其2月4日至帳戶#1的每日餘額,但忘記爲帳戶#5輸入「X」價格,您應該每個對於特定股票具有不同的「最後輸入日期」帳戶。實際上最好有兩張桌子......一張只有你的股票,截止日期和收盤價。然後將其加入到使用這些股票的賬戶中......但是,該查詢應該爲您提供每個賬戶的詳細分類,顯示所有最大的相應股票日期......下一個查詢將簡化爲每個賬戶的總計...這一個主要是爲了保證你得到你想要的健康檢查。這是所有的帳戶,但你可以調整你的WHERE子句,只有一個特定的帳戶,如果你需要。現在

SELECT 
     ticker, 
     account, 
     closingdate, 
     quantity, 
     closing, 
     (quantity*closing) as "Net" 
    FROM 
     "stock values" AS S, 
     (select account, 
       ticker, 
       max(closingdate) LastDatePerStock 
      from 
       "stock values" sMax 
      group by 
       account, ticker) TickerDate 
    WHERE 
      s.account = TickerDate.account 
     and s.ticker = TickerDate.ticker 
     and s.closingdate = TickerDate.LastDatePerStock 
     and (quantity>0.000001) 
    order by 
     account, 
     ticker 

,查詢簡單,只需賬戶,期末借款餘額爲他們的所有股票,沒有看到什麼股票投資組合。

SELECT 
     account, 
     max(closingdate) LatestClosingDate, 
     sum((quantity*closing)) as "Net" 
    FROM 
     "stock values" AS S, 
     (select account, 
       ticker, 
       max(closingdate) LastDatePerStock 
      from 
       "stock values" sMax 
      group by 
       account, ticker) TickerDate 
    WHERE 
      s.account = TickerDate.account 
     and s.ticker = TickerDate.ticker 
     and s.closingdate = TickerDate.LastDatePerStock 
     and (quantity>0.000001) 
    group by 
     account