不知道在哪里放置子查询中的位置

时间:2016-06-24 06:15:36

标签: sql sql-server

我想制作一个view来查找字符库存中前5个最高数量的商品,还有一个列显示其他人也有该商品的数量。

  • CHARACTERS

    • CHARID PK
  • INVENTORY

    • ITEMID
    • CHARID
  • ITEM
    • ITEMID

这是我到目前为止所得到的,

CREATE VIEW vwPopItems --Top 5 most popular items
AS
SELECT TOP 5 INVENTORY.itemID, CHARACTERS.charName,quantity,
       (SELECT COUNT(*) FROM INVENTORY where INVENTORY.itemID =) as cnt
FROM INVENTORY
JOIN CHARACTERS
ON CHARACTERS.charID = INVENTORY.charID
WHERE INVENTORY.charID = 6
GO

而是将count显示为该表中没有WHERE的所有记录,因此我需要制作一个WHERE,只显示前5个特定项目的$("button").click(function(){ // add button click event var value = $("#concept_name").val(); if(value.length > 50){ alert("Maximum limit is 50 character"); return false; // it will not submit form if return false }else{ alert("Form will be submitted"); return true; } });同样具有该项目的字符数量。知道上面的错误但是你们能告诉我该怎么做才能解决它吗? :)

2 个答案:

答案 0 :(得分:3)

只需使用COUNT(*)而不是子查询。然后使用TOP和ORDER BY to get the TOP` 5。

SELECT TOP(5)
    i.itemID,
    c.charName,
    i.quantity,
    COUNT(*) AS cnt
FROM INVENTORY i
INNER JOIN CHARACTERS c
    ON c.charID = i.charID
WHERE
    i.charID = 6
GROUP BY 
    i.itemID,
    c.charName,
    i.quantity,
ORDER BY cnt DESC

答案 1 :(得分:0)

SELECT EMPLOYEE_ID, salary, department_id
FROM   employees E
WHERE salary > (SELECT AVG(salary)
                FROM   EMP T
                WHERE E.department_id = T.department_id)