2011-08-31 110 views
0

我有產品表& priceDeatil表。Android sqlite/Ms sql/sql查詢

Prouct Table 
ProductCode BusinessUnit 
10001  ORB   
10002  ORB   

StockRecord Table 
ProductCode Name  StcokQuantity 
    10001   SUnSilk 1000 
    10002   Pen   500 

priceDeatil 
ProductCode BusinessUnit price DateFrom  DateTo 
10001   ORB   12.00 12-08-2011 31-09-2015 
10001   ORB   21.00 01.08-2011 15-09-2011 
10002   ORB   54.00 21.08-2011 15-09-2011 

我想要得到的產品表中的記錄,StockRecords的表&價格與產品的最新價格

這裏PRODUCTCODE 10001包含2條記錄,當我運行查詢它返回2個reords.I想只有一個記錄。

SELECT  WMProduct.BusinessUnit, WMProduct.ProductCode, StockRecord.Name, WMPriceDetail.Price 
FROM  WMProduct INNER JOIN StockRecord 
      ON WMProduct.ProductCode = StockRecord.ProductCode 
      INNER JOIN WMPriceDetail 
      WMPriceDetail ON WMProduct.BusinessUnit = WMPriceDetail.BusinessUnit AND WMPriceDetail.ProductCode = WMProduct.ProductCode 

WHERE  (WMPriceDetail.DateFrom < GETDATE()) AND (WMPriceDetail.DateTo > GETDATE() OR 
      WMPriceDetail.DateTo = NULL) 

該查詢返回

BusinessUnit ProductCode  Name Price 
    ORB   10001   SunSilk 12.00 
    ORB   10001   SunSilk 21.00 

但我只需要一個記錄.... BusinessUnit產品代碼名稱價格 ORB 10001夏士蓮21.00 ORB 10002筆54.00

從該查詢我不能放TOP 1因爲有更多的表結合..加入

如果價格未在價格明細表中定義,則該記錄不應顯示在列表中。

請幫我....提前

回答

0

試試這個朋友:

select p.businessunit, p.productcode, pr.price from 
WMProduct p ,WMStockRecord s, WMPriceDetail pr 
where p.productcode = s.productcode and 
    s.productcode = pr.productcode and p.productcode=pr.productcode and 
    pr.datefrom = (select max(datefrom) from WMPriceDetail where productcode = p.productcode and 
    (
    (DateFrom < 'Sep 06 2011') AND (DateTo > 'Sep 06 2011' OR DateTo IS NULL) 
) 
0

您可以使用頂部1

感謝有加入...

只是不要選擇前1等。正如你已經完成。 所以

select top 1 a.name, b.name from table1 a join table2 b on a.id=b.id 

你的第二個問題是,你不一定會得到正確的行返回你沒有做之前對結果進行排序前1

--update

似乎SQLite不理解頂部,但確實理解LIMIT。 見http://www.sqlite.org/lang_select.html

請注意,您仍然需要通過條款

+0

沒有它的不工作... – Piraba

+0

見上面更新 – Blootac

1

我怎麼uderstood您需要priceDetail只有最高價使用命令:

SELECT WMProduct.BusinessUnit, 
     WMProduct.ProductCode , 
     WMProduct.Description , 
     price_detail.price 
FROM WMProduct 
     INNER JOIN 
       (SELECT MAX(Price) AS price, 
         BusinessUnit  , 
         ProductCode 
       FROM  WMPriceDetail 
       GROUP BY BusinessUnit, 
         ProductCode 
      ) 
       price_detail 
     ON  price_detail.BusinessUnit = WMProduct.BusinessUnit 
     AND price_detail.ProductCode = WMProduct.ProductCode 
WHERE (
       WMPriceDetail.DateFrom < GETDATE() 
     ) 
AND 
     (
       WMPriceDetail.DateTo > GETDATE() 
     OR  WMPriceDetail.DateTo = NULL 
     ) 
+0

它說'多部分標識符「WMPriceDetail.DateFrom」不能bound.'。而不是'MAX(價格)'。它應該是'MAX(DateFrom)' – Piraba

+0

忘了where where =)在你需要的子選擇字段中添加並且不要忘記關於分組 – cetver

+0

我認爲你的假設是錯誤的。我需要最新的定義價格(DateFrom)和那個日期憤怒不應該是完成日期(與GETDATE()比較)。不工作,我得到了錯誤消息 – Piraba