说我有一张像这样的表
ID | FieldA | FieldB | FieldC | GroupID
---------------------------------------
1 | 50 | NULL| 80 | 1
2 | NULL | 60 | NULL | 1
3 | 70 | NULL| 50 | 1
我想生成一个按降序显示非NULL值的行(按ID) 所以结果表看起来像这样
ID | FieldA | FieldB | FieldC | GroupID
---------------------------------------
3 | 70 | 60| 50 | 1
有没有办法在MySQL中执行此操作? 我试过了:
SELECT *
FROM (table)
GROUP BY GroupID
ORDER BY ID DESC
但没有运气(当然)
这是一个小提琴,所以你可以快速玩这个!
http://sqlfiddle.com/#!2/71846f/2
谢谢!
答案 0 :(得分:1)
如果没有每列的子查询,这可能是不可能的:
SELECT
(SELECT `ID` FROM `table1` ORDER BY `ID` DESC LIMIT 1) AS `ID`,
(SELECT `FieldA` FROM `table1` WHERE `FieldA` IS NOT NULL ORDER BY `ID` DESC LIMIT 1) AS `FieldA`,
(SELECT `FieldB` FROM `table1` WHERE `FieldB` IS NOT NULL ORDER BY `ID` DESC LIMIT 1) AS `FieldB`,
(SELECT `FieldC` FROM `table1` WHERE `FieldC` IS NOT NULL ORDER BY `ID` DESC LIMIT 1) AS `FieldC`,
(SELECT `GroupID` FROM `table1` WHERE `GroupID` IS NOT NULL ORDER BY `ID` DESC LIMIT 1) AS `GroupID`
答案 1 :(得分:0)
您应该检查您的字段,如下所示:
SELECT *
FROM table
WHERE FieldA is not null
AND FieldB is not null
AND FieldC is not null
ORDER BY ID DESC
答案 2 :(得分:0)
select MAX(feA),
MAX(feB),
MAX(feC)
from test05
答案 3 :(得分:0)
仅按组ID分组,然后选择所有列的最大值。 。 哪个会有所帮助
SELECT max(id),max(FIELDA),max(FIELDB),max(FIELDC),GroupID
FROM (table)
GROUP BY GroupID
答案 4 :(得分:0)
如果您想要FIELD的最小值,那么您只需要这个。 此查询未经过测试 如果此查询出现任何错误,请回复
SELECT max(id),max(FIELDA),max(FIELDB),min(FIELDC),GroupID
FROM (test)
GROUP BY GroupID
答案 5 :(得分:0)
您可以创建列名为1-20的CTE(将原始数据复制到其中)
然后您将选择每一列(max(列))并将其更新为临时表。
(将原始表复制到temp并截断它。)
使用column_number和dynamic sql上的循环执行此操作。
我希望你明白我的意思 - :)