我写了以下查询
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张优惠券,但它没有显示
答案 0 :(得分:0)
我认为您可能需要使用RIGHT JOIN
从Coupon
表中获取所有记录。
答案 1 :(得分:0)
似乎自RIGHT JOIN
起作用并给出正确的答案(可能是虚假的用户ID),而LEFT JOIN
根本没有给出与优惠券相关的任何结果,优惠券是在非现有用户上注册。
LEFT JOIN
要求数据存在于表格的左侧,可能存在于右侧,而RIGHT JOIN
则相反。换句话说,数据存在于最右边的表格(优惠券)中,与左侧(用户)没有任何连接
答案 2 :(得分:0)
您没有使用正确的联接。 您想获得用户ID的优惠券吗? 使用此联接。 从 用户对我们而言 LEFT JOIN 优惠券c ON us.Id = c.Userid 如果这不起作用,那么使用: 从 用户对我们而言 LEFT OUTER JOIN 优惠券c ON us.Id = c.Userid