SQL Count with Inner Join for Single Table

大憨熊 提交于 2019-12-25 08:35:54

问题


I have a table like this:

Name    Id      Amount 
Name1   1       99
Name1   1       30
Name1   9       120.2
Name2   21      348
Name2   21      21
Name3   41      99

I want to select each name, group them by their id and count the transactions (NOT SUM). So I want the following table:

Name    Id      Count 
Name1   1       2
Name1   9       1
Name2   21      2
Name3   41      1

I tried this sql:

SELECT
    [Name],
    [Id]
FROM table1 A
INNER JOIN (
                SELECT
                [Id],
                count([Amount]) as 'Count'
                FROM 
                    table1
                GROUP BY [Id]
           )
B ON A.[Id] = B.[Id]

But I get the following error: Ambiguous column name 'Id'.

What am I doing wrong?


回答1:


SELECT
       [Name],
       [Id],
       count([Amount]) as 'Count'
FROM 
       table1
GROUP BY [Name], [Id]



回答2:


SELECT
A.[Name],
A.[Id]
FROM table1 A
INNER JOIN (
            SELECT
            table1.[Id],
            count([Amount]) as 'Count'
            FROM 
                table1
            GROUP BY table1.[Id]
       )
B ON A.[Id] = B.[Id]


来源:https://stackoverflow.com/questions/42261204/sql-count-with-inner-join-for-single-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!