我有一个存储过程:
ALTER PROCEDURE [dbo].[p_GetOrdersList]
@OrderID int = NULL,
@UserID int = NULL,
@IsCompleted smallint = NULL
AS
BEGIN
select
tto.OrderID, tto.DateAdded, tto.ItemsCount, tto.TotalAmount,
ttu.FirstName, ttu.LastName, ttu.Email,
ISNULL(ttu.FirstName,'') + ' ' + ISNULL(ttu.LastName,'') FullUserName,
tuq.QuoteStatusID
from
tbl_Orders tto
join
tbl_Users ttu on tto.UserID = ttu.UserID
where
tto.OrderID = ISNULL(@OrderID,tto.OrderID)
AND tto.UserID = ISNULL(@TronixUserID,tto.TronixUserID)
AND EXISTS (SELECT *
FROM tbl_UserQuotes ttuq
WHERE ttuq.OrderID = tto.OrderID
AND ttuq.QuoteStatusID = ISNULL(@IsCompleted, ttuq.QuoteStatusID)
)
--QuoteStatusID: 4.Completed other than 4 are Pending/Incomplete/Processing
END
在上面的查询中,我想仅在tbl_Orders
表中的所有行都有tbl_UserQuotes
即QuoteStatusID = 4
时才从表Completed
中获取所有记录。如果即使单行不是4,那么它也不能出现在列表中。
MasterTable(tbl_Orders)
OrderID ITemsCount TotalAmount
1 1 100
2 2 200
3 2 300
DetailTable(tbl_UserQuotes)
DetailID OrderID Amount QuoteStatusID
1 1 100 4
2 2 100 2
3 2 100 4
4 3 150 4
5 3 150 4
Result Must be:
OrderID TotalAmount
1 100
3 300
答案 0 :(得分:1)
请尝试以下查询:
SELECT tbl_orders.orderid,
Sum(amount)
FROM tbl_orders
INNER JOIN tbl_userquotes
ON tbl_orders.orderid = tbl_userquotes.orderid
WHERE tbl_orders.orderid <> (SELECT orderid
FROM tbl_userquotes
WHERE quotestatusid <> 4)
GROUP BY tbl_orders.orderid
<强> SQL DEMO 强>
答案 1 :(得分:1)
这是我的解决方案:
Select tto.OrderID,tto.DateAdded,tto.ItemsCount,tto.TotalAmount,
ttu.FirstName,ttu.LastName,ttu.Email ,ISNULL(ttu.FirstName,'') + ' ' + ISNULL(ttu.LastName,'') FullUserName
from tbl_Orders tto join tbl_Users ttu
on tto.UserID = ttu.UserID
where tto.OrderID = ISNULL(@OrderID,tto.OrderID)
AND tto.UserID = ISNULL(@UserID,tto.UserID)
AND tto.ItemsCount= (
select count(orderid) from tbl_UerQuotes where orderid=tto.OrderID and quotestatusid=4
)
ORDER BY tto.DateAdded DESC
答案 2 :(得分:0)
**Please Try this query**
select mt.orderId,sum(dt.amount)
from MasterTable as mt inner join DetailTable as dt on mt.orderid=dt.orderid
group by orderid having quotestatusid=4