我正在从三个不同的表中检索
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_orderQuantity
,只需要lc_orderID
求和,即lc_orders_tb
和lc_orderQuantity_tb
。
有人可以帮帮我..
提前谢谢。
答案 0 :(得分: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;
答案 1 :(得分:0)
除了Aaron的解决方案(我更喜欢)之外,如果您没有使用不支持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;
您还可以在SQL 2005 +
中使用CROSS APPLY
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