SQL Server:根据另一个表中的值汇总一个表中的col

时间:2013-08-27 12:32:10

标签: sql sql-server-2008 count

如果只有一个表中的值存在于另一个表中,我该如何求值。

例如 table1 - typeOfBiscuits

biscuits
jaffacakes
digestives

table2 - inventry
type number
digestives 2
digestives 3
jaffacakes 2
digestives 3
jaffacakes 4
cheesecake 1

select Count(number) from Inventry where type = <not sure how to get type from typeOfBisuit table>

的预期结果
type count
digestives 8
jaffacakes 6

我的尝试如下,但我得到了对多部分字符串&#39;的引用。错误

select Count(number) from Inventry where type = typeOfBiscuits.type

3 个答案:

答案 0 :(得分:1)

SELECT typeOfBiscuits.biscuits, Sum(Inventory.Number) as [Count]
FROM typeOfBiscuits INNER JOIN Inventory
ON typeOfBiscuits.biscuits = Inventory.type
GROUP BY typeOfBiscuits.type

答案 1 :(得分:0)

请尝试:

SELECT 
 t1.Type,
 SUM(number) as [Count]
FROM
 inventry t1 INNER JOIN typeOfBiscuits t2 ON t1.Type=t2.Type
GROUP BY t1.Type

答案 2 :(得分:0)

试试这个:

SELECT TYPE, 
       Sum(NUMBER) AS [Count] 
FROM   TABLE2 
WHERE  TYPE IN (SELECT TYPEOFBISCUITS 
                FROM   TABLE1) 
GROUP  BY TYPE