2

我写了以下查询

SELECT 
   us.Id as Id, us.Name as Name,
   SUM(CASE WHEN c.isPublish = 0 THEN 1 ELSE 0 END) AS PendingCoupons,
   SUM(CASE WHEN c.isPublish = 1 and convert(date,c.PublishedDate,101) >=  convert(date, GETDATE(), 101) THEN 1 ELSE 0 END) AS ApprovedCouponsToday,
   SUM(CASE WHEN c.isPublish = 0 and convert(date,c. CreateDate, 101) = convert(date, GETDATE(), 101) THEN 1 ELSE 0 END) AS PendingCouponsToday,
   SUM(CASE WHEN c.isPublish = 1 THEN 1 ELSE 0 END) AS ApprovedCoupons,
   SUM(CASE WHEN c.isPublish = 1 and c.Userid = us.Id and convert(date, c.PublishedDate, 101) >= convert(date, GETDATE(), 101) THEN 1 ELSE 0 END) AS ApprovedByUserToday,
   SUM(CASE WHEN c.isPublish = 1 and c.Userid = us.Id THEN 1 ELSE 0 END) AS ApprovedByUser,
   SUM(CASE WHEN c.ReviewVerify = 1 and convert(date, c.PublishedDate, 101) >= convert(date, GETDATE(), 101) THEN 1 ELSE 0 END) AS ProcessToday,
   COUNT(*) AS Total
FROM 
   Users AS us
LEFT JOIN 
   Coupon c ON Userid = us.Id
GROUP BY 
   us.Name , us.Id

我有以下两张桌子

表

在运行上面的查询之后,结果总是这样

结果

这个查询是否有任何错误,因为它总是返回我计数“0”,我每个用户都有近 100 张优惠券但它没有显示

4

3 回答 3

0

我认为您可能需要使用 a从表RIGHT JOIN中获取所有记录Coupon

于 2012-10-09T10:26:27.880 回答
0

看起来,由于RIGHT JOIN有效并给出了正确的答案(可能是虚假的用户 ID),而 aLEFT JOIN根本没有给出与优惠券相关的任何结果,优惠券在非现有用户上注册。

LEFT JOIN要求数据存在于表的左侧,而右侧则可能存在,RIGHT JOIN反之亦然。换句话说,数据存在于最右边的表(优惠券)中,与左侧(用户)没有任何联系

于 2012-10-09T11:50:56.640 回答
0

您没有使用正确的连接。您想获得用户 ID 的优惠券吗?使用此联接。FROM Users AS us LEFT JOIN Coupon c ON us.Id = c.Userid 如果这不起作用,则使用: FROM Users AS us LEFT OUTER JOIN Coupon c ON us.Id = c.Userid

于 2012-10-09T13:00:44.387 回答