查询以选择属于未返回的用户的每个产品的最后订单(条目)

时间:2011-09-21 17:30:47

标签: sql tsql sql-server-2008

我陷入了相当混乱的问题。

假设我有一个ProductLending表,它跟踪每个用户借用的产品,更新时间,是否返回等等。鉴于用户,我希望能够选择所有仍然存在的独特产品用户。

表示例:

userid    DateRenewed    ProductId    isReturned
````````````````````````````````````````````````
1        2011-07-21      15           0
1        2011-08-20      16           0
1        2011-09-21      15           1
2        2011-09-21      17           0
1        2011-09-21      15           0

这是一个模拟,如果它不准确,那就很抱歉。

现在,给定userId = 1,我想只选择未返回但与用户一起使用的唯一productId。所以这应该给我 15,16 ,因为即使返回了15,它也被重新借用了。如果我们删除最后一行,那么结果将只是16,因为用户只有16个人。

我尝试通过dateRenewed进行排序并选择前1名,但它确实完成了其他内容..如何为此构建查询?

3 个答案:

答案 0 :(得分:2)

如果用户未退回产品,则购买产品的总和必须大于退回产品的总和

SELECT userid,ProductId FROM <table>
GROUP BY userid,ProductId HAVING SUM(CASE CAST(isReturned AS INT) WHEN 0 THEN 1 ELSE 0 END)-SUM(CAST(isReturned AS INT))>0

答案 1 :(得分:1)

试试这个:

;WITH qry AS
(
  SELECT *, 
         ROW_NUMBER() OVER(PARTITION BY userID, ProductID ORDER BY DateRenewed DESC) rn
    FROM YourTable
)
SELECT * 
  FROM qry
WHERE rn = 1 AND isReturned = 0;

答案 2 :(得分:0)

select distinct ProductId
from TABLE_NAME t1
where UserId= @UserId 
and IsReturned = 0
and not exists
(
   select *
   from TABLE_NAME t2
   where t2.UserId =  t1.UserId
   and  t2.ProductId = t1.ProductId
   and t2.IsReturned = 1 
   and t2.DateRenewed > t1.DateRenewed
)