我在表中有8列。所有列都是相同类型的整数。
|id | marks_1 | marks_2 | marks_3|....|marks_7|
|1001|0 |20 |15 |....|25 |
|1002|20 |0 |11 |....|0 |
.
.
.
.
|1010|40 |0 |0 |....|25 |
我希望输出为
|id |marks |
|1001|15 |
|1002|11 |
我尝试使用MySql的LEAST()函数获取最少的这些列。
SELECT id, LEAST(marks_1,marks_2,marks_3,marks_4,marks_5,marks_6,marks_7) AS marks from tbl_name
它正在发挥作用。
它抓住了我
|id |marks |
|1001|0 |
|1002|0 |
但我需要第二个。即行中的非零记录。
答案 0 :(得分:3)
如果您想要的是大于0
的最小数字,那么您可以取消您的表并对其应用分组:
SELECT id, MIN(c)
FROM (
SELECT id,
CASE t2.n
WHEN 1 THEN col_1
WHEN 2 THEN col_2
WHEN 3 THEN col_3
WHEN 4 THEN col_4
WHEN 5 THEN col_5
WHEN 6 THEN col_6
WHEN 7 THEN col_7
END AS c
FROM mytable AS t1
CROSS JOIN (
SELECT 1 AS n UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7) AS t2) AS x
WHERE x.c > 0
GROUP BY id
答案 1 :(得分:2)
试试这个:
$(".dropdown-toggle").removeAttr("href");
答案 2 :(得分:1)
您可以通过规范化数据和使用变量来实现:
select t.*
from (select t.*,
(@rn := if(@id = id, @rn + 1,
if(@id := id, 1, 1)
)
) as rn
from ((select id, col_1 as col, 'col_1' as colname from t) union all
(select id, col_2 as col, 'col_2' as colname from t) union all
. . .
) t cross join
(select @rn := 0, @id := -1) params
order by id, col asc
) t
where rn = 2;
注意:此版本还提供列名称。您需要使用所有其他列填写. . .
。
答案 3 :(得分:0)
这不好,但也有效:
SELECT
id
, SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(col1 ORDER BY col1), ',', -3),',',1)
FROM (
SELECT id, col1 FROM test_table
UNION SELECT id, col2 FROM test_table
UNION SELECT id, col3 FROM test_table
UNION SELECT id, col4 FROM test_table
UNION SELECT id, col5 FROM test_table
) AS t
GROUP BY t.id
ORDER BY t.col1
;
<强>样品强>
mysql> SELECT
-> id
-> , SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(col1 ORDER BY col1), ',', -3),',',1)
-> FROM (
-> SELECT id, col1 FROM test_table
-> UNION SELECT id, col2 FROM test_table
-> UNION SELECT id, col3 FROM test_table
-> UNION SELECT id, col4 FROM test_table
-> UNION SELECT id, col5 FROM test_table
-> ) AS t
-> GROUP BY t.id
-> ORDER BY t.col1
-> ;
+----+-----------------------------------------------------------------------------------+
| id | SUBSTRING_INDEX(SUBSTRING_INDEX(GROUP_CONCAT(col1 ORDER BY col1), ',', -3),',',1) |
+----+-----------------------------------------------------------------------------------+
| 1 | 3 |
| 2 | 6 |
+----+-----------------------------------------------------------------------------------+
2 rows in set (0,00 sec)
mysql> select * from test_table;
+----+------+------+------+------+------+
| id | col1 | col2 | col3 | col4 | col5 |
+----+------+------+------+------+------+
| 1 | 1 | 3 | 2 | 5 | 4 |
| 2 | 7 | 8 | 6 | 3 | 2 |
+----+------+------+------+------+------+
2 rows in set (0,00 sec)
mysql>