【问题标题】:Add rows count in SQL view在 SQL 视图中添加行数
【发布时间】:2025-11-25 03:10:01
【问题描述】:

我正在尝试使用 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;

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

【问题讨论】:

    标签: sql database view


    【解决方案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;
    

    或者,加入一个group by;

    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;
    

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

    【讨论】:

    • 效果很好!!谢谢!!
    【解决方案2】:

    这不是创建表,你正在加入

    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 command = new SqlCommand(commandStr, con)) command.ExecuteNonQuery();

    你需要这样

    【讨论】:

    • 粘贴答案时标签/窗口错误?
    【解决方案3】:

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

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

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

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

    【讨论】:

    • 从我添加到问题的代码中,您可以看到我阅读并理解了这部分,并且我知道 COUNT 是如何工作的,您提出的网站很棒,但那里没有我的问题的答案.