【问题标题】:How to get the total count of two columns from two different tables in SQL Server?如何从 SQL Server 中的两个不同表中获取两列的总数?
【发布时间】:2015-12-18 05:09:54
【问题描述】:

我在 SQL Server 中有 2 个表,Table1Table2

Table1 包含户主的年龄信息,Table2 包含家庭成员的年龄信息。

我想获得总年龄。表示如果用户在前端输入的人数少于 23,那么我将向用户显示两个表中年龄小于 23 的总人数。

我的做法是这样的:

alter procedure example 
   (@age int, @result2 int output)
as
begin
    declare @result int;
    declare @result1 int;

    set @result = (select count(age) from Table1 where age > @age)
    set @result1 = (select count(age) from Table2 where age > @age)

    set @result2 = @result + @result1;
end

hvcid 是我的Table1 中的主键列,hvcid 是我的Table2 中的外键。

上面显示的我的查询返回结果很好。为什么不使用join或者single query来组合两张表,得到两张表的总年龄?

我不知道如何使用单个查询编写?你能解决我的问题吗?

【问题讨论】:

    标签: c# sql-server


    【解决方案1】:

    您可以使用以下查询从 2 个表中获取结果:

    select count(age) + (select count(age) 
        from Table2 where age > @age) 
    from Table1 where age > @age
    

    【讨论】:

    • 是的,但我可以从前端调用 ExecuteNonQuery() 吗?那么它是否会在这种方法中给出结果?请如果是或否,我如何使用 c# 将这个结果发送到前端?
    • No.ExecuteNonQuery() 结果为-1。但是您的 select 语句给出了正确的结果。
    • ExecuteScalar() 方法运行良好 Aliasgar 谢谢老兄。
    【解决方案2】:

    另一种方式

    SELECT Sum(cnt) AS total
    FROM   (SELECT Count(age) cnt
            FROM   Table1
            WHERE  age > @age
            UNION ALL
            SELECT Count(age)
            FROM   Table2
            WHERE  age > @age) a 
    

    【讨论】:

      【解决方案3】:

      试试这个 @Nag

      select (COUNT(t1.age) + COUNT(t2.age)) as Result
      from Table1 t1 
      FULL JOIN Table2 t2 on t1.hvcid = t2.hvcid
      where t1.age > @age and t2.age > @age
      

      【讨论】:

      • @Nag - 如果你使用 ExecuteScalar(query) 那么你会从代码中得到结果......希望这会有所帮助......
      • @khled 这个查询给出了一些小错误,我的表中有 5 条记录。表 1 中有 2 条记录,表 2 中有 3 条记录,所以我的表中只有 5 人,但它给出的年龄计数为 6。如果我输入 >14 岁的人。
      • @Nag - 我认为你必须使用 FULL JOIN 而不是 INNER JOIN 然后......因为我认为 Table2 中有一个额外的 hvcid,而 Table1 中没有......但是你想要两个表的所有记录....查看我编辑的答案...所以使用 FULL JOIN 而不是 INNER JOIN ...希望这会有所帮助..
      • @kheeld 但如何获取两张桌子之间的年龄?我认为完全加入给出了相同的结果?我可以从两张桌子上取 23 到 25 之间的前吗?
      • 是的,我自己试过了,然后我才问没有尝试,我不会问谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-06-21
      • 1970-01-01
      • 2022-06-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多