我想写一个查询,用于选择状态1&的第一条记录。状态2的第二记录等等
我喜欢
+----+--------+--------+
| id | name | status |
+----+--------+--------+
| 1 | ABC | 1 |
| 2 | PQR | 1 |
| 3 | qqq | 2 |
| 4 | www | 1 |
| 5 | eee | 2 |
| 6 | rrr | 2 |
| 7 | ttt | 2 |
+----+--------+--------+
我需要一个如下所示的输出
+----+-------+---------+
| id | name | status |
+----+-------+---------+
| 1 | ABC | 1 |
| 3 | qqq | 2 |
| 2 | PQR | 1 |
| 5 | eee | 2 |
| 4 | www | 1 |
| 6 | rrr | 2 |
| 7 | ttt | 2 |
+----+-------+---------+
记录序列应该是那样的
- 1st record with status 1
- 2nd record with status 2
- 3rd record with status 1
- 4th record with status 2
- 5th record with status 1
- 6th record with status 2
- 状态为2的第7条记录 - >如果我们找不到状态为1的记录,则选择状态为2&的记录。反之亦然
我通过编码得到了这个输出但是MySQL查询可能得到这样的输出
答案 0 :(得分:3)
您可以使用变量:
SELECT id, name, status
FROM (
SELECT id, name, status,
@grp := IF(@status = status, @grp + 1,
IF(@status := status, 1, 1)) AS grp
FROM mytable
CROSS JOIN (SELECT @grp := 0, @status := 0) AS vars
ORDER BY status, name) AS t
ORDER BY grp, status, name
使用的算法中的关键是变量@grp
:它基本上模拟ROW_NUMBER() OVER (PARTITION BY status)
。使用@grp
,我们可以通过交替 status
效果轻松实现顺序。
答案 1 :(得分:1)
procedure InitializeWizard();
var
CustomStatusLabel: TNewStaticText;
begin
WizardForm.FilenameLabel.Visible := False;
WizardForm.StatusLabel.Visible := False;
WizardForm.ProgressGauge.Top := WizardForm.InstallingPage.Height - ScaleY(60);
CustomStatusLabel := TNewStaticText.Create(WizardForm);
CustomStatusLabel.Parent := WizardForm.InstallingPage;
CustomStatusLabel.Caption := 'Installing Colectica';
CustomStatusLabel.Font.Size := CustomStatusLabel.Font.Size + 4;
CustomStatusLabel.Font.Style := [fsBold];
CustomStatusLabel.AutoSize := True;
CustomStatusLabel.Top :=
WizardForm.ProgressGauge.Top - CustomStatusLabel.Height - ScaleY(8);
CustomStatusLabel.Left :=
WizardForm.ProgressGauge.Left +
((WizardForm.ProgressGauge.Width - CustomStatusLabel.Width) div 2);
end;
答案 2 :(得分:-1)
您可以使用此查询SELECT rownum FROM TABLE GROUP BY rownum HAVING mod(rownum,2)=0