简体   繁体   English

SQL 基于列条件查询

[英]SQL query based on column condition

I have a sql table in which below are the columns.我有一个 sql 表,其中下面是列。 I'm using sql server.我正在使用 sql 服务器。

Id ID name姓名 isActive活跃 device设备
1 1 Motorola摩托罗拉 1 1 phone电话
1 1 Motorola摩托罗拉 0 0 tablet药片

Need to have a SQL query for below scenario:需要对以下场景进行 SQL 查询:

I want to display firstdevice , seconddevice columns below based on isActive column.我想根据isActive列在下面显示firstdeviceseconddevice列。 If isACTIVE is 1 then, fill the device name in firstdevice column, if isActive is 0 then fill the device name in secondDevice .如果isACTIVE1 ,则在firstdevice列中填写设备名称,如果isActive0 ,则在secondDevice中填写设备名称。

Id ID name姓名 firstDevice第一个设备 secondDevice第二个设备
1 1 Motorola摩托罗拉 phone电话 tablet药片

I assume you have only maximum 2 rows per id and name我假设每个 id 和 name 最多只有 2 行

select id, name, 
MAX(DECODE(isActive, 1, device)) AS firstDevice,
MAX(DECODE(isActive, 0, device)) AS secondDevice
from table
group by 
id, name;
select id, name, 
MAX(CASE when isActive = 1 then device end) AS firstDevice,
MAX(CASE when isActive = 0 then device end) AS secondDevice
from table
group by 
id, name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM