我有两张桌子; hotelservices and guestorder
hotelservices
s_id(pk) serviceType serviceName
guestOrder表:
g_id(pk) serviceType totalAmount balanceDue PaidAmount orderDate
我想根据hotelservice表中的serviceType获取totalAmount,balanceDue,PaidAmount的总和。
也就是说,它会迭代并对hotelservices.serviceType进行分组,并根据serviceType列从guestorder表中获取关联数据。
到目前为止我的尝试:
SELECT
g.OrderDate as saleDate,
g.ServiceType,
sum(g.TotalAmount) as TotalSales,
sum(g.BalanceDue) as TotalBalanceDue,
sum(g.PaidAmount) as TotalPaid,
h.ServicesType as services
FROM guestorder as g join hotelservices as h on g.ServiceType=h.ServicesType
group by saleDate
但这不是我想要的。我需要它来显示其他serviceType,即使它在guestorder中没有任何内容。我不知道我是否有意义。提前谢谢
答案 0 :(得分:0)
也许反转你的联接,把它变成LEFT OUTER JOIN并用你的GROUP BY解决问题,例如:
SELECT
g.OrderDate as saleDate,
g.ServiceType,
sum(g.TotalAmount) as TotalSales,
sum(g.BalanceDue) as TotalBalanceDue,
sum(g.PaidAmount) as TotalPaid,
h.ServicesType as services
FROM
hotelservices as h
LEFT JOIN guestorder as g ON g.ServiceType=h.ServicesType
GROUP BY
g.OrderDate,
g.ServiceType,
h.ServicesType;
答案 1 :(得分:0)
i need it to show others serviceType even if it has nothing in the guestorder
从这个我假设您有不匹配的数据... 当你使用JOIN或INNER JOIN(因为那是JOIN默认的)时,你会过滤掉任何不匹配的东西。如果你想在没有过滤的情况下加入,那就做一个LEFT JOIN ..
你应该添加COALESCE(),这样就不会有像这样的NULL值
SELECT
COALESCE(g.OrderDate, '') saleDate,
COALESCE(g.ServiceType, '') guestServiceType,
COALESCE(sum(g.TotalAmount), 0) TotalSales,
COALESCE(sum(g.BalanceDue), 0) TotalBalanceDue,
COALESCE(sum(g.PaidAmount), 0) TotalPaid,
h.ServicesType as services
FROM hotelservices h
LEFT JOIN guestorder g ON g.ServiceType = h.ServicesType
GROUP BY h.serviceType, saleDate
您的选择需要来自酒店服务表,以便您拥有所有服务类型..然后LEFT JOIN guestorder表,这样就没有过滤。