列x必须出现在GROUP BY子句中,或者用在聚合函数中

时间:2015-09-10 19:54:39

标签: sql postgresql greatest-n-per-group

SELECT newTable.book_id
FROM (
    SELECT book_id, SUM(stock) AS stock
    FROM editions JOIN stock ON (editions.isbn = stock.isbn)
    GROUP BY book_id

    ) AS newTable
HAVING stock = max(stock);

我希望这段代码能够生成书中的book_id,其中大部分都是有库存的,即库存中书籍的最高份数。我收到以下错误:

ERROR:  column "newtable.book_id" must appear in the GROUP BY clause or be used in an aggregate function
LINE 2:  SELECT newTable.book_id
                ^

********** Error **********

ERROR: column "newtable.book_id" must appear in the GROUP BY clause or be used in an aggregate function

任何解决方案?

PS。已经尝试在最后添加GROUP BY newtable.book_id, newtable.stock。它生成了语法错误。

谢谢!

1 个答案:

答案 0 :(得分:0)

我认为您可以考虑编写如下查询。您只需按照汇总的列进行排序,这样最“库存”将位于顶部,然后使用LIMIT子句从顶部取出X项。在这种情况下,LIMIT 1。

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
[RequireComponent(typeof(CapsuleCollider))]

public class SoldierController : MonoBehaviour
{

    public GameObject grenadeObject;

     void Start()
        {
            grenadeObject.SetActive(false); 
        }

    void Update()
    {
     if (Input.GetKeyDown(KeyCode.I))
                    {
                        grenadeObject.SetActive(true);
                        animator.SetBool("Grenade", true);
                        GrenadeThrow();
                        //speed = Mathf.Lerp(10, 0, Time.deltaTime);
                       // grenadeObject.transform.Translate(Vector3.forward * 10);
                        StartCoroutine(GrenadeCooldown());
                    }

     }

    void GrenadeThrow()
        {
            StartCoroutine(COPlayOneShot("Grenade"));
            Instantiate(grenadeObject, new Vector3(10 * 2.0F, 0, 0), Quaternion.identity);
        }


        IEnumerator GrenadeCooldown()
        {
            canFire = false;
            yield return new WaitForSeconds(0.01f);
            //rifleMuzzle.GetComponent<ParticleSystem>().top();
            canFire = true;
            animator.SetBool("Grenade",false);
        }
}