对于pubs
我想将stores表中的stor_name添加到查询中,但它不起作用。
查询是:
SELECT
title, COALESCE(SUM(S.qty * T.price), 0) totalsale
FROM
titles T
LEFT JOIN
sales S ON (S.title_id = T.title_id)
GROUP BY
title
ORDER BY
2 DESC
我需要在stor_name
表格中添加store
。如果我尝试像这样添加它
SELECT
title, COALESCE(SUM(S.qty * T.price), 0) totalsale, stores.stor_name
FROM
titles T
LEFT JOIN
sales S ON (S.title_id = T.title_id)
JOIN
stores ON (S.stor_id = stores.stor_id)
GROUP BY
title
HAVING
stores.stor_name
ORDER BY
2 DESC
返回的结果是错误的。
答案 0 :(得分:0)
您需要在GROUP BY
中包含该名称或作为聚合函数的参数。类似的东西:
SELECT title, COALESCE(SUM(S.qty*T.price), 0) as totalsale, st.stor_name
FROM titles T LEFT JOIN
sales S
ON (S.title_id = T.title_id) JOIN
stores st
ON S.stor_id = st.stor_id)
GROUP BY title, st.stor_name
ORDER BY 2 desc;
或者,如果您只想要其中一个名字,那么:
SELECT title, COALESCE(SUM(S.qty*T.price), 0) as totalsale,
MAX(st.stor_name)
FROM titles T LEFT JOIN
sales S
ON (S.title_id = T.title_id) JOIN
stores st
ON S.stor_id = st.stor_id)
GROUP BY title
ORDER BY 2 desc;