我有下表名为Messages:
ID | CustomerID | CarID | TruckID | CreatedByID | Date
1 23 null null 2343 1/27/2014
2 null 56 null 2343 1/27/2014
3 null null 78 2343 1/27/2014
消息可以与客户,汽车或卡车相关联。 Car Car和Truck也将拥有CustomerID,因此虽然特定消息可能是Car,但它也与客户相关联。
a)在上面的示例中,如果Car 56和Truck 78都属于Customer 23,则客户2343帮助的总数为1.
b)如果Car 56和Truck 78属于不同的客户,则总数为3。我现在确定如何查询这个,我有这个查询,但它应该只给我汽车的总数(大多数消息将用于汽车)。
(SELECT CreatedByID, count(distinct(CarID)) AS Count
FROM Messages
WHERE CarID is not null
AND CreatedDate >= @StartDate
AND CreatedDate <= @EndDate
AND CreatedByID IN
(SELECT UserID FROM @UserIDs)
GROUP BY CreatedByID
) TotalCustomers on TotalCustomers .CreatedByID = u.UserID
所以在示例b中我应该只得到1,但那不正确。
如何修改此项以考虑示例b?
@UsersIDs是一个只有UserIDs的临时表
我尝试了这个,但我不认为这是正确的(并没有考虑卡车,我不确定它可以)。此外,我对CreatedByID进行了硬编码,当我尝试将查询更改为具有与上述类似的分组时,我无法正确执行此操作。
select CarID
from Card
where CustomerID not in (
select CustomerID
from Messages
where CustomerID is not null
and CreatedByID = 2343
and CreateDate >= @StartDate
AND CreateDate <= @EndDate
)
and CarID in (
select CarID
from Messages
where CarID is not null
and CreatedByID = 2343
and CreateDate >= @StartDate
AND CreateDate <= @EndDate
)
答案 0 :(得分:3)
您的数据每封邮件只定义一个实体。假设是这种情况,你可以这样做:
select coalesce(m.customerid, c.customerid, t.customerid) as customerid, count(*) as cnt
from Messages m left outer join
Cars c
on m.carid = c.carid left outer join
Trucks t
on m.truckid = t.truckid
group by coalesce(m.customerid, c.customerid, t.customerid);
您可以为示例代码建议的其他过滤添加where
子句。
注意:count(*)
假定至少有一个ID与其他表中的一个匹配。
答案 1 :(得分:1)
如果您想要帮助的客户数量,按createdByID
小计,那么它将是这样的:
SELECT m.createdByID
--, m.CreatedDate --if you wanted the count of customers helped by date, then un-comment this line
, COUNT(DISTINCT COALESCE(m.CustomerID, c.CustomerID, t.CustomerID)) as CustomersHelpedCount
FROM [Messages] m
LEFT JOIN Cars c ON m.carID = c.carID
LEFT JOIN Trucks t on t.truckID = m.truckID
WHERE m.CreatedDate between @StartDate and @EndDate
AND m.createdByID in (SELECT UserID FROM @UserIDs)
GROUP BY m.createdBy
--, m.CreatedDate --if you wanted the count of customers helped by date, then un-comment this line