我有一张像
这样的出勤表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'应该被忽略,并且一行中剩余列的总和应添加并显示在最后一列的行
中答案 0 :(得分:0)
我建议您使用NULL而不是'a',但如果您使用MySql,则可以使用以下内容:
SELECT
user_name, Col, col2, Col3, Col4, Col1+Col2+Col3+Col4
FROM
yourtable
WHERE 'a' IN (Col, Col2, Col3, Col4)
请参阅小提琴here。
答案 1 :(得分:0)
在 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
答案 2 :(得分:0)
在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。