在SQL视图中添加行计数

时间:2015-03-03 20:05:49

标签: sql database view

我尝试使用SQL视图创建表。它假设在问题表中的每一行添加一列,该列将具有给予该问题的答案的整数值。这就是我到目前为止所做的:

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;

我明白这是不对的,但我无法想到别的。请帮忙!

3 个答案:

答案 0 :(得分:1)

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

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子句中列出的。

答案 1 :(得分:0)

这不是创建表,而是加入

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();

你需要这样

答案 2 :(得分:-1)

如果您要COUNT所有条目,您可以使用此:

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

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

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