[英]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 ![]() |
name![]() |
isActive![]() |
device![]() |
---|---|---|---|
1 ![]() |
Motorola![]() |
1 ![]() |
phone![]() |
1 ![]() |
Motorola![]() |
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
列在下面显示firstdevice
, seconddevice
列。 If isACTIVE
is 1
then, fill the device name in firstdevice
column, if isActive
is 0
then fill the device name in secondDevice
.如果
isACTIVE
为1
,则在firstdevice
列中填写设备名称,如果isActive
为0
,则在secondDevice
中填写设备名称。
Id ![]() |
name![]() |
firstDevice![]() |
secondDevice![]() |
---|---|---|---|
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.