使用 having by 子句过滤导致 having 子句中的未知列
filtering using having by clause result in unknown column in having clause
我有一个包含这些列的 table:order_date(采用 yyyy-mm-dd 格式)、order_status、product_sub_category、销售额。数据包含 2009 年以后的交易。我想要做的是找到 2011 年和 2012 年之间每个产品类别的总销售额。为此,我使用这些查询:
SELECT
YEAR(order_date) AS years,
product_sub_category,
SUM(sales) AS sales
FROM dqlab_sales_store
WHERE
order_status = 'order finished'
AND product_sub_category = 'Chairs & Chairmats'
OR product_sub_category = 'Office Machines'
OR product_sub_category = 'Tables'
OR product_sub_category = 'Copiers and Fax'
OR product_sub_category = 'Telephones and Communication'
GROUP BY
YEAR(order_date), product_sub_category
HAVING
YEAR(order_date) > 2011;
问题是 sql 告诉我 having 子句中的未知列 'order_date'
有什么解决办法吗?谢谢
您不能在同一查询中使用 having 和 where。
试试这个:
SELECT a.years, a.product_sub_category, sum(sales) as sales
FROM(
SELECT
YEAR(order_date) AS years,
product_sub_category,
sales
FROM dqlab_sales_store
WHERE
order_status = 'order finished'
AND (product_sub_category = 'Chairs & Chairmats'
OR product_sub_category = 'Office Machines'
OR product_sub_category = 'Tables'
OR product_sub_category = 'Copiers and Fax'
OR product_sub_category = 'Telephones and Communication')) as a
GROUP BY
a.years,
a.product_sub_category
HAVING
a.years > 2011;
我有一个包含这些列的 table:order_date(采用 yyyy-mm-dd 格式)、order_status、product_sub_category、销售额。数据包含 2009 年以后的交易。我想要做的是找到 2011 年和 2012 年之间每个产品类别的总销售额。为此,我使用这些查询:
SELECT
YEAR(order_date) AS years,
product_sub_category,
SUM(sales) AS sales
FROM dqlab_sales_store
WHERE
order_status = 'order finished'
AND product_sub_category = 'Chairs & Chairmats'
OR product_sub_category = 'Office Machines'
OR product_sub_category = 'Tables'
OR product_sub_category = 'Copiers and Fax'
OR product_sub_category = 'Telephones and Communication'
GROUP BY
YEAR(order_date), product_sub_category
HAVING
YEAR(order_date) > 2011;
问题是 sql 告诉我 having 子句中的未知列 'order_date'
有什么解决办法吗?谢谢
您不能在同一查询中使用 having 和 where。 试试这个:
SELECT a.years, a.product_sub_category, sum(sales) as sales
FROM(
SELECT
YEAR(order_date) AS years,
product_sub_category,
sales
FROM dqlab_sales_store
WHERE
order_status = 'order finished'
AND (product_sub_category = 'Chairs & Chairmats'
OR product_sub_category = 'Office Machines'
OR product_sub_category = 'Tables'
OR product_sub_category = 'Copiers and Fax'
OR product_sub_category = 'Telephones and Communication')) as a
GROUP BY
a.years,
a.product_sub_category
HAVING
a.years > 2011;