2012-04-17 100 views
0

[解決:感謝bluefeet和Brian我建立這個工作查詢(原來我還需要第四個表/圖)」SQL查詢得到基於parentId的表B記錄表一

SELECT  A.SalesLineID, A.ArticleResultID, B.ID, C.ID, D.Value 
FROM   VIEWA AS A 
       INNER JOIN TABLEB AS B ON A.ArticleResultID = B.ArticleResultID 
       AND B.Name = N'Collect' AND DAPR.Value = 1 
       INNER JOIN TABLEC AS C ON B.ArticleResultID = C.ID 
       AND C.Name='Assemble' 
       AND C.Value = 1 
       INNER JOIN TABLED AS D ON D.ArticleResultID = C.ParentId 
       AND D.Name = 'IndexY' 
WHERE  (A.SalesID = @SalesID) 

[更新:我犯了一個錯誤,假設IndexY/Color和ProdId其中字段表A是某種只有5列ID - 名稱 - 值 - ARTICLERESULTID - PRODID的參數/屬性表。IndexY是Name字段的值。 。]

我無法構建正確的sql查詢來完成此技巧:

我有以下2個表:

Table A 
ID Name   Value ArticleResultID  ProdID Color 
1 Operation Collect    110   10 BLACK 
2 IndexY   10    110   10 - 
3 Operation Collect    101   11 WHITE 


Table B 
ID ParentID Name  Value  
101 110  Assemble  1  
101 100  Assemble  0  

步驟:

Find record in A with Name = Operation and Value = Collect and ProdId = 11 AS ORG_A 
Find record in B With B.ID = ORG_A.ArticleResultId AND B.NAME = 'Assemble'AND B.VALUE = 1 AS B 
Find record in A With A.ArticleResultID = B.ParentID as NEW_A 

在上面的情況那ORG_A.ArticleResultID = 11 - > B.ParentID = 110 - > NEW_A.ARTICLERESULTID = 110 - >(IndexY - 值 - 10)

非常感謝,如果有人能告訴我如何建立這個查詢..

最好的問候,

邁克·d

[老描述:]

我無法建立正確的SQL查詢來獲取這一招做:

我有以下2個表:

Table A 
Name  Value ArticleResultID  IndexY  Color ProdID 
Operation Collect    110   10   -  0 
Operation Collect    101   _  Black  100 


Table B 
ID ParentID Name  Value Dx  Dy 
101 110  Assemble  1  1000 500 
101 100  Assemble  0  400  300 

我想要從A中取得所有記錄,其中NAME等於'operation',VALUE等於'Collect'且PRODID ='100',但我也希望(這是我的問題)表A中記錄的IndexY值與PARENTID表B wh ichArticleResultID AND Name ='Assemble'and VALUE ='1'

在上面的場景中,ParentID 110向TableA提供帶ArticleY(10)的ArticleResultID 110的記錄, 。

非常感謝,如果有人能告訴我如何建立這個查詢..

最好的問候,

邁克·d

回答

2

由於您的要求不是最清楚的。這個怎麼樣:

SELECT a1.*, a2.indexy as additionalIndexY 
FROM ta a1 
INNER JOIN tb b 
    ON a1.articleresultid = b.id 
INNER JOIN ta a2 
    ON b.parentid = a2.articleresultid 
WHERE a1.name = 'Operation' 
    AND a1.prodid = 100 
    AND b.name = 'Assemble' 
    AND b.value = 1 

這裏是一個sqlfiddle一個工作版本

如果你只是想用110 articleresultid記錄,則:

SELECT a2.* 
FROM ta a1 
INNER JOIN tb b 
    ON a1.articleresultid = b.id 
INNER JOIN join ta a2 
    ON b.parentid = a2.articleresultid 
WHERE a1.name = 'Operation' 
    AND a1.prodid = 100 
    AND b.name = 'Assemble' 
    AND b.value = 1 

看到sqlfiddle對第二個例子

+0

Thnx bluefeet,但是我錯誤地描述了這個問題。希望我的更新更清楚一點... – 2012-04-18 08:35:32

2

這是否對你的工作?

SELECT a.*,c.IndexY 
    FROM [TableA] a 
    JOIN [TableB] b ON a.ArticleResultId = b.id 
       AND b.Name ='Assemble' 
       AND b.Value = 1 
    JOIN [TableA] c ON b.ParentId = c.ArticleResultID 
    WHERE a.name = 'Operation' 
    AND a.Value = 'Collect' 
    AND a.ProdId = 100