0

因为pubs我想将存储表中的 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_namestore表中添加一个。如果我尝试像这样添加它

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

返回的结果是错误的。

在此处输入链接描述

4

1 回答 1

0

您需要将名称包含在GROUP BYor 作为聚合函数的参数。就像是:

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;
于 2016-09-26T23:29:41.460 回答