如何连接两个表并计算值的出现次数?

时间:2016-07-13 04:56:39

标签: sql-server

我有这些表格:

CREATE TABLE [dbo].[Word] 
(
    [WordId]        UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
    [Name]          VARCHAR (20)     NOT NULL,
    [Ascii]         AS               (ascii([Name])) PERSISTED,
    PRIMARY KEY CLUSTERED ([WordId] ASC)
);

CREATE TABLE [dbo].[WordForm] 
(
    [WordFormId]   UNIQUEIDENTIFIER DEFAULT (newid()) NOT NULL,
    [WordId]       UNIQUEIDENTIFIER NOT NULL,
    [SourceId]     INT              DEFAULT ((1)) NOT NULL,
    CONSTRAINT [PK_WordForm] PRIMARY KEY CLUSTERED ([WordFormId] ASC),
);

有没有办法可以加入这两个表并显示每个不同ascii值的计数,其中第二个表中的SourceId的值为1?

返回类似的内容:

a  25
b  30
c  22
d  10

2 个答案:

答案 0 :(得分:1)

您可以在select语句中使用内部联接...

SELECT W.Ascii, COUNT(1)
FROM
    [dbo].[Word] W
    INNER JOIN [dbo].[WordForm] WF
        ON WF.WordId = W.WordId
WHERE
    WF.SourceId = 1
GROUP BY
    W.Ascii

答案 1 :(得分:1)

你的意思是这样的:

SELECT W.Ascii, COUNT(*) AS [Count] FROM Word W
INNER JOIN WordForm WF
ON W.WordId = WF.WordId
WHERE W.WordId = 1
GROUP BY W.Ascii