2011-06-27 66 views
0

我從三個不同的表總和的sql

SELECT lc_orders_tb.lc_orderID, lc_orders_tb.lc_orderSubTotal, lc_orders_tb.lc_orderTotal, lc_orders_tb.lc_orderPlacedDate, lc_tb.lc_compName, lc_tb.lc_addCity, lc_orderQuantity_tb.lc_orderID, 
    sum(lc_orderQuantity_tb.lc_orderQuantity) 
AS lc_orderQuantity 
FROM lc_orders_tb, lc_orderQuantity_tb, lc_tb 
WHERE lc_orders_tb.lc_id=lc_tb.lc_id 
AND lc_orderQuantity_tb.lc_orderID=lc_orders_tb.lc_orderID 
GROUP BY lc_orderQuantity_tb.lc_orderID 

檢索我要顯示在GridView上面檢索到的值。對於特定的lc_orderID,只需要對lc_orderQuantity進行求和,其必須與兩個表匹配,即lc_orders_tblc_orderQuantity_tb

有人可以幫我出來嗎..

在此先感謝您。

+0

應指定和/或與您正在使用SQL Server的實際版本標籤;解決方案可能有所不同 –

回答

0

隨着亞倫的解決方案(我喜歡)你也可以在情況下,嵌入式查詢你不使用DB不支持WITH條款

聯查詢從

SELECT 
    o.lc_orderID, 
    o.lc_orderSubTotal, 
    o.lc_orderTotal, 
    o.lc_orderPlacedDate, 
    lc.lc_compName, 
    lc.lc_addCity, 
    q.lc_orderQuantity 
FROM 
    dbo.lc_orders_tb AS o 
INNER JOIN 
    ( SELECT lc_OrderID, lc_OrderQuantity = SUM(lc_orderQuantity) 
     FROM dbo.lc_orderQuantity_tb 
     GROUP BY lc_OrderID) q ON o.lc_orderID = q.lc_OrderID 
INNER JOIN 
    dbo.lc_tb AS lc 
    ON o.lc_id = lc.lc_id; 

,或在SELECT子句

SELECT 
     o.lc_orderID, 
     o.lc_orderSubTotal, 
     o.lc_orderTotal, 
     o.lc_orderPlacedDate, 
     lc.lc_compName, 
     lc.lc_addCity, 
     (SELECT SUM(lc_orderQuantity) 
      FROM dbo.lc_orderQuantity_tb o 
      WHERE o.lc_orderID = q.lc_OrderID 
     ) as lc_orderQuantity 
    FROM 
     dbo.lc_orders_tb AS o 
     INNER JOIN 
     dbo.lc_tb AS lc 
     ON o.lc_id = lc.lc_id; 

您還可以使用CROSS APPLY在SQL 2005+

SELECT 
     o.lc_orderID, 
     o.lc_orderSubTotal, 
     o.lc_orderTotal, 
     o.lc_orderPlacedDate, 
     lc.lc_compName, 
     lc.lc_addCity, 
     q.lc_orderQuantity 
    FROM 
     dbo.lc_orders_tb AS o 
     INNER JOIN 
     dbo.lc_tb AS lc 
     ON o.lc_id = lc.lc_id 
     CROSS APPLY 
     (SELECT 
      SUM(lc_orderQuantity) lc_orderQuantity 
     FROM 
      lc_orderQuantity_tb t 
     WHERE o.lc_orderID = t.lc_orderID) q 
+0

非常感謝,您的解決方案正常工作..再次感謝您。 – newBie

1
;WITH q AS 
(
    SELECT lc_OrderID, lc_OrderQuantity = SUM(lc_orderQuantity) 
     FROM dbo.lc_orderQuantity_tb 
     GROUP BY lc_OrderID 
) 
SELECT 
    o.lc_orderID, 
    o.lc_orderSubTotal, 
    o.lc_orderTotal, 
    o.lc_orderPlacedDate, 
    lc.lc_compName, 
    lc.lc_addCity, 
    q.lc_orderQuantity 
FROM 
    dbo.lc_orders_tb AS o 
INNER JOIN 
    q ON o.lc_orderID = q.lc_OrderID 
INNER JOIN 
    dbo.lc_tb AS lc 
    ON o.lc_id = lc.lc_id; 
+0

+1,但可能不適用於OP,因爲它不清楚它們使用的是什麼DB –

+0

感謝@Conrad。問題的標題說「ms sql」 - 我認爲這是Microsoft SQL Server。答案將在2005年以及更高版本上發揮作用,並且我還對提出了一個版本的問題添加了評論。 –

+0

是的,我站在糾正。 –