C# 如果行中有char值,如何对行求和
我有一张像这样的考勤表C# 如果行中有char值,如何对行求和,c#,asp.net,mysql,sql,sql-server,C#,Asp.net,Mysql,Sql,Sql Server,我有一张像这样的考勤表 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
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而不是“a”,但如果您使用MySql,您可以使用类似以下内容:
SELECT
user_name, Col, col2, Col3, Col4, Col1+Col2+Col3+Col4
FROM
yourtable
WHERE 'a' IN (Col, Col2, Col3, Col4)
请查看fiddle。在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
在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
请看小提琴
除了替换,您还可以使用CASE语句。为什么这不是一个数值数据类型,用
NULL
表示不存在?事实上,为什么你有31列呢?只要有一个带有empno、date、value的表,每个考勤记录都有一行。你到底在用什么RDBMS?@MartinSmith是对的。一个月的每一天(二月怎么样?)都有一个专栏,既浪费又低效。只需将员工缺席的日期记录为date
s,如果没有特定日期的记录,则表示该员工出席了会议。首先,您的数据库设计得很糟糕。一种解决方案是,您需要使用case语句,将a更改为o,并转换为整数来查找和。这是行不通的(实际上DV在MySQL中可能会被收回。如果您尝试“a”+3+76+56),SQL Server肯定会给出错误)@MartinSmith为什么您说它行不通?我添加了一个提琴,mysql允许您这样做queries@MartinSmith好的,问题标记为sql server和mysql,我在回答中指定它只在mysql中有效是的,我根据上面的编辑收回了我的DV。OP同时标记了MySQL和SQL Server。