【问题标题】:How to sum the rows if it has a char value in the row如果行中有char值,如何对行求和
【发布时间】:2013-03-25 10:58:12
【问题描述】:

我有一个像这样的考勤表

user_name     |   Col  |   col2   |   Col3  |  Col4 + other columns.

person1       |  a     |  3       | 76      | 56  etc.    ---------> sum of row

person2       |  6     |  72      | a       | 13  etc.    ---------> sum of row

其中“a”表示不存在,因此我需要添加一行中的所有列并显示在最后一列中,即“total”中,这样​​应该忽略“a”并计算一行中剩余列的总和应该添加并显示在最后一列的行中

【问题讨论】:

  • 为什么这不是NULL 代表不存在的数字数据类型?事实上,为什么你有 31 列?只需有一个带有empno,date,value 的表格,每个出勤记录都有一行。您实际使用的是什么 RDBMS?
  • @MartinSmith 是对的。每个月的每一天(二月呢?)的专栏既浪费又低效。只需将员工缺勤的日期记录为dates,如果没有特定日期的记录,则表示该员工出席了。
  • 首先您的数据库设计不佳。一种解决方案是您需要使用 case 语句并将 a 更改为 o 并转换为整数以求和。

标签: c# asp.net mysql sql sql-server


【解决方案1】:

我建议你使用 NULL 而不是 'a' 但是如果你使用 MySql 你可以使用这样的东西:

SELECT
  user_name, Col, col2, Col3, Col4, Col1+Col2+Col3+Col4
FROM
  yourtable
WHERE 'a' IN (Col, Col2, Col3, Col4)

请看小提琴here

【讨论】:

  • 这是行不通的(实际上DV在MySQL中可能会被收回。如果你尝试''a' + 3 + 76 +56,SQL Server肯定会出错)
  • @MartinSmith 为什么你说它不起作用?我添加了一个小提琴,mysql允许你这样的查询
  • @MartinSmith 好的,问题被标记为 sql-server 和 mysql,我在回答中指定它只适用于 mysql
  • 是的,我按照上面的编辑收回了我的 DV。 OP 已标记 MySQL 和 SQL Server。
【解决方案2】:

在 MSSQL 中这有效:

SELECT
  user_name, Col, col2, Col3, Col4, 
  CAST(REPLACE(Col, 'a', '0') AS INT)+
  CAST(REPLACE(Col2, 'a', '0') AS INT)+
  CAST(REPLACE(Col3, 'a', '0') AS INT)+
  CAST(REPLACE(Col4, 'a', '0') AS INT)
FROM
  yourtable

请看小提琴here

您也可以使用 CASE 语句来代替 REPLACE。

【讨论】:

    【解决方案3】:

    mysql

    中试试这个
         SELECT
          user_name, Col, col2, Col3, Col4, Col+Col2+Col3+Col4 as sum
         FROM
          yourtable
    

    这个在 sql server

     SELECT
     user_name, Col, col2, Col3, Col4 ,
     case when col = 'a'
                then cast(col2 as int ) + cast(col3 as int ) +cast(col4 as int )
     when col2 = 'a'
                then cast(col as int ) + cast(col3 as int ) +cast(col4 as int )
     when col3 = 'a'
                then cast(col as int ) + cast(col2 as int ) +cast(col4 as int )
     when col4 = 'a'
                then cast(col as int ) + cast(col2 as int ) +cast(col3 as int )
    else  cast(col as int )+ cast(col2 as int ) + cast(col3 as int ) +cast(col4 as int)     
     end    as sum_all
    
     FROM
      yourtable
    
     group by user_name , col , col2, col3,col4
    

    DEMO HERE

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-10-18
      • 2021-11-30
      相关资源
      最近更新 更多