在 SQL 视图中添加行数

Add rows count in SQL view

我正在尝试使用 SQL 视图创建 table。它假设在问题 table 的每一行中添加一列,该列将具有对该问题给出的答案的整数值。这是我目前所拥有的:

CREATE VIEW [dbo].[Question]
AS
    SELECT 
       COUNT(answer.Id) as 'Answers',
       question.Id,
       question.CreatorId,
       question.Title,
       question.Content,
       question.CreationDate
    FROM 
       Questions AS question 
    JOIN 
       Answers AS answer ON answer.QuestionId = question.Id;

我知道这是不对的,但我想不出别的。请帮忙!

这不是创建 table,您正在加入

var commandStr= "If not exists (select name from sysobjects where name = 'Customer') CREATE TABLE Customer(First_Name char(50),Last_Name char(50),Address char(50),City char(50),Country char(25),Birth_Date datetime)";

使用 (SqlCommand 命令 = new SqlCommand(commandStr, con)) command.ExecuteNonQuery();

你需要这样

我最喜欢的相关子查询计数:

CREATE VIEW [dbo].[Question]
AS
SELECT (select COUNT(*) from Answers
        where QuestionId = question.Id) as 'Answers',
       question.Id,
       question.CreatorId,
       question.Title,
       question.Content,
       question.CreationDate
FROM Questions AS question;

或者,加入一个分组依据;

CREATE VIEW [dbo].[Question]
AS
SELECT COUNT(answer.Id) as 'Answers',
       question.Id,
       question.CreatorId,
       question.Title,
       question.Content,
       question.CreationDate
FROM Questions AS question 
JOIN Answers AS answer
ON  answer.QuestionId = question.Id
GROUP BY question.Id,
         question.CreatorId,
         question.Title,
         question.Content,
         question.CreationDate;

请注意,select 列表中的列要么是聚合函数的参数,要么也列在 GROUP BY 子句中。

如果你想计算所有条目,你可以使用这个:

CREATE VIEW [dbo].[Question] AS
SELECT COUNT(*) AS amount FROM Questions

如果您需要更复杂的 COUNTing(或其他聚合函数),请查看该页面:

http://www.w3schools.com/sql/sql_func_count.asp