【问题标题】:SQL Server : multiple Select queriesSQL Server:多个选择查询
【发布时间】:2020-01-25 16:12:52
【问题描述】:

我试图在同一个结果屏幕中同时显示sum(grand_total) where is_loyal = 1 和sum(grand_total) where is_loyal = 0(grand_total 列在同一个表中)。我已经尝试过子查询、加入和大小写,但到目前为止还没有运气。有没有办法一起计算和显示结果?

我可以通过子查询找到的唯一结果如下,无论我如何更改 where 子句都会给我相同的数据。如果我稍微改变我的查询,它会抛出错误消息

消息 512,第 16 级,状态 1,第 155 行
子查询返回超过 1 个值。当子查询跟随 =、!=、、>= 或子查询用作表达式时,这是不允许的。

Result

【问题讨论】:

    标签: sql-server tsql select


    【解决方案1】:

    使用条件聚合:

    select date,
      sum(case when loyal = 1 then grand_total end) [Total Loyalty],
      sum(case when loyal = 0 then grand_total end) [Total Spent non-loyalty]
    from tablename
    group by date
    

    【讨论】:

      【解决方案2】:

      这样的用例:

      select
      sum(case when loyal = 1 then 1 else 0 end) as grand_total_Loyal,
      sum(case when loyal = 0 then 1 else 0 end) as grand_total_noneloyal
      

      【讨论】:

      • ::Facepalm:: 以不同且不成功的方式尝试了案例,现在我看到了我的错误:))非常感谢伙计!
      • 此查询似乎缺少from 子句和group by 子句。
      • 嗨,GMB,我刚刚给了他他在问题中要求的部分。但是确实是其余的我没有添加它
      • 谢谢你们,非常感谢。我处理了其余的查询,我完全错误地使用了 case 子句,现在我明白了我的错误。
      • @forpas 对不起,如果我选择了错误的答案作为正确答案。
      【解决方案3】:

      一个简单的方法使用算术:

      select sum(loyal * grandtotal) as loyal_grandtotal,
             sum( (1 - loyal)  * grandtotal) as notloyal_grandtotal
      from t
      where loyal in (1, 0);
      

      更通用的解决方案是使用case 表达式。然而,如果你有 0/1 标志,它们很容易适合算术计算——因为它们比字符串标志更受欢迎。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多