专栏" INVOICE.DATE_OF_ISSUE"在ORDER BY子句中无效,因为它不包含在聚合函数或GROUP BY子句中

时间:2017-01-10 12:18:07

标签: sql sql-server

有人可以解释一下我做错了什么吗?我完全是新手,我不知道该怎么做。

我试图显示1995年7月17日至1995年7月24日期间发出的Invoice:nr_invoice和发票金额,净值超过50,全部按日期排序。

SELECT INVOICE.NR_INVOICE, COUNT(COMMODITY.PRICE)
FROM INVOICE FULL JOIN LINE_INVOICE ON INVOICE.NR_INVOICE = LINE_INVOICE.FNR_INVOICE
 LEFT JOIN COMMODITY ON LINE_INVOICE.FID_TOWAR = COMMODITY.ID_COMMODITY
WHERE INVOICE.DATE_OF_ISSUE BETWEEN '1995-07-17' AND '1995-07-24'
  and COMMODITY.PRICE > 50
GROUP BY INVOICE.NR_INVOICE
ORDER BY INVOICE.DATE_OF_ISSUE

这是一个错误

  

专栏" INVOICE.DATE_OF_ISSUE"在ORDER BY子句中无效,因为它不包含在聚合函数或GROUP BY子句中。

3 个答案:

答案 0 :(得分:2)

没有理由为此查询使用外连接。无论如何,你的where条款正在将它们变成内连接。

要解决您的特定问题,您需要在DATE_OF_ISSUE中加入GROUP BY或使用汇总功能:

SELECT i.NR_INVOICE, COUNT(c.PRICE)
FROM INVOICE i JOIN
     LINE_INVOICE li
     ON i.NR_INVOICE = li.FNR_INVOICE JOIN
     COMMODITY c
     ON li.FID_TOWAR = c.ID_COMMODITY
WHERE i.DATE_OF_ISSUE BETWEEN '1995-07-17' AND '1995-07-24' AND
      c.PRICE > 50
GROUP BY i.NR_INVOICE, i.DATE_OF_ISSUE
ORDER BY i.DATE_OF_ISSUE;

编辑:

您的具体问题是:

  

我试图显示发票:nr_invoice和发票金额   1995年7月17日至1995年7月24日期间,净值更高   超过50,全部按日期排序。

对此的查询将使用HAVING

SELECT i.NR_INVOICE, SUM(c.PRICE)
FROM INVOICE i JOIN
     LINE_INVOICE li
     ON i.NR_INVOICE = li.FNR_INVOICE JOIN
     COMMODITY c
     ON li.FID_TOWAR = c.ID_COMMODITY
WHERE i.DATE_OF_ISSUE BETWEEN '1995-07-17' AND '1995-07-24' 
GROUP BY i.NR_INVOICE, i.DATE_OF_ISSUE
HAVING SUM(c.PRICE) > 50
ORDER BY i.DATE_OF_ISSUE;

注意:如果您在发票行中有数量值,则需要考虑该值。

答案 1 :(得分:1)

您不能使用该列,因为它不在GROUPING中(如错误所述)。您可以按列的总和(根据您的需要的最小值或最大值)进行订购。像这样:

SELECT INVOICE.NR_INVOICE, COUNT(COMMODITY.PRICE)
FROM INVOICE FULL JOIN LINE_INVOICE ON INVOICE.NR_INVOICE = LINE_INVOICE.FNR_INVOICE
 LEFT JOIN COMMODITY ON LINE_INVOICE.FID_TOWAR = COMMODITY.ID_COMMODITY
WHERE INVOICE.DATE_OF_ISSUE BETWEEN '1995-07-17' AND '1995-07-24'
  and COMMODITY.PRICE > 50
GROUP BY INVOICE.NR_INVOICE
ORDER BY MIN(INVOICE.DATE_OF_ISSUE)

答案 2 :(得分:1)

SELECT INVOICE.NR_INVOICE, COUNT(COMMODITY.PRICE)
FROM INVOICE FULL JOIN LINE_INVOICE ON INVOICE.NR_INVOICE = LINE_INVOICE.FNR_INVOICE
 LEFT JOIN COMMODITY ON LINE_INVOICE.FID_TOWAR = COMMODITY.ID_COMMODITY
WHERE INVOICE.DATE_OF_ISSUE BETWEEN '1995-07-17' AND '1995-07-24'
  and COMMODITY.PRICE > 50
GROUP BY INVOICE.NR_INVOICE
ORDER BY min(INVOICE.DATE_OF_ISSUE)