postgresql Sql查询-按列中真值的数量排序

ne5o7dgx  于 2022-12-26  发布在  PostgreSQL
关注(0)|答案(3)|浏览(145)

我有一张这样的table

我需要根据最后4列中真值的数量来获得有效性顺序。例如,以下查询的输出应为

1110  // 4 true values
1001  // 2 true values
1000 // 1 true value
nhaq1z21

nhaq1z211#

可以使用子查询;

SELECT subquery.VALIDITY,
concat(CAST ((subquery.TAXI + subquery.CAR + subquery.TRUCK + subquery.BIKE) AS TEXT) , ' True values') as COUNTTRUEVALUES
FROM (select VALIDITY,
CASE WHEN TAXI THEN 1 ELSE 0 END AS TAXI,
CASE WHEN CAR THEN 1 ELSE 0 END AS CAR,
CASE WHEN TRUCK THEN 1 ELSE 0 END AS TRUCK,
CASE WHEN BIKE THEN 1 ELSE 0 END AS BIKE
FROM YourTableName) as subquery
ORDER BY 2 DESC

输出

VALIDITY COUNTTRUEVALUES

1110      4 True values
1001      2 True values
1000      1 True values
ztyzrc3y

ztyzrc3y2#

将布尔值转换为整数,并按其总和降序排列:

SELECT *
FROM tablename
ORDER BY taxi::int + car::int + truck::int + bike::int DESC;

请参见demo

lsmepo6l

lsmepo6l3#

像这样的怎么样?

SELECT 
id,
validity,
taxi1 + car1 + truck1 + bike1
FROM 
(
SELECT
id,
validity
CASE WHEN taxi = 'TRUE' THEN 1 ELSE 0 END taxi1,
CASE WHEN car = 'TRUE' THEN 1 ELSE 0 END car1,
CASE WHEN truck = 'TRUE' THEN 1 ELSE 0 END truck1,
CASE WHEN bike = 'TRUE' THEN 1 ELSE 0 END bike1
FROM table
)

相关问题