Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/powerbi/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql server 根据列值选择列_Sql Server_Sql Server 2012 - Fatal编程技术网

Sql server 根据列值选择列

Sql server 根据列值选择列,sql-server,sql-server-2012,Sql Server,Sql Server 2012,我有一张五列的桌子 ID INT、Reading1 INT、Reading2 INT、Status1 INT、Status2 INT 如果reading1值大于reading2值,我想选择reading1,并想用它选择status1值。如果reading2值大于reading1值,则我要选择reading2值和status2值 我已经试过了,但它给了我一个错误: select ID, case when reading1 > reading2 then reading1 w

我有一张五列的桌子

ID INT、Reading1 INT、Reading2 INT、Status1 INT、Status2 INT

如果reading1值大于reading2值,我想选择reading1,并想用它选择status1值。如果reading2值大于reading1值,则我要选择reading2值和status2值

我已经试过了,但它给了我一个错误:

select ID, 
       case when reading1 > reading2 then reading1 when reading2 > reading1 then reading2 as readings,
       case when reading1 > reading2 then status1 when reading2 > reading1 then status2 as status
from table 
我的表格数据

ID  Reading1    Reading2    Status1 Status2
1   113 88  1   0
2   176 22  2   -1
3   204 39  3   -1
4   99  107 0   1
5   86  103 0   1
6   78  101 0   1
7   100 53  1   0

查询中的CASE语句缺少结尾。试试这个:

select ID, 
       case when reading1 > reading2 then reading1 when reading2 > reading1 then reading2 end as readings,
       case when reading1 > reading2 then status1 when reading2 > reading1 then status2 end as status
from table;
如果读取1=读取2,则尚未定义规则。您可以使用ELSE执行此操作,如下所示:

SELECT ID, 
       CASE WHEN reading1 > reading2 THEN reading1 WHEN reading2 > reading1 THEN reading2 ELSE reading1 END AS readings,
       CASE WHEN reading1 > reading2 THEN status1 WHEN reading2 > reading1 THEN status2 ELSE status1 END AS status
FROM table;
参考


使用CASE语句,您可以执行以下操作

SELECT ID 
       ,CASE WHEN reading1 > reading2 
             THEN reading1 ELSE reading2 END as readings
       ,CASE WHEN reading1 > reading2 
             THEN status1 ELSE status2  END as [status]
FROM table 
但由于您使用的是
SQLServer2012
,因此也可以使用新的
IIF()
语句

SELECT ID
      , IIF(Reading1 > Reading2, Reading1, Reading2)   AS [Reading]
      , IIF(Reading1 > Reading2, [Status1], [Status2]) AS [Status]
FROM TABLE


您的条件无法处理您可能希望将比较更改为
=的情况,如果两个值相等,至少会返回一些结果。

您可以格式化代码以删除水平滚动条。您的case语句中的第二个条件是不必要的,您可以在那里使用其他条件。因为只有两列要比较。