作为查询的一部分,我有以下内容(我戴着学习者徽章!)......
SELECT
Main.Ax,
Main.Ay,
(select Astr from Afull where Avalid = Main.Ax) as AxStr,
(select Astr from Afull where Avalid = Main.Ay) as AyStr,
Switch(AxStr>=0, AxStr,AxStr<0,0,isnull(AxStr),0)
+ Switch(AyStr>=0, AyStr,AyStr<0,0,isnull(AyStr),0) as AStrTotal
FROM Main
但是,当我尝试包含Order By 5 Asc
时,我遇到了一个问题,即它不起作用。我猜这与之前的2个子查询有关(然后AStrTotal将它们加在一起)。
此外,是否可以在不必使用绝对位置的情况下引用别名字段位置(上面的5,对于AStrTotal)?
编辑:更多背景信息......
Table Main(要搜索的主数据库)包括2个字段Ax和Ay
Ax Ay
1 6
5 9
3 3
7
5 5
7 2
2
4 4
3
6 5
7 6
等....上面的空白条目只是空值。 Ax和Ay值可以出现在任一字段中。
表Afull包含2个名为Avalid和Astr ...
的字段Avalid AStr
1
2
3
4
5
6
7
8
9
Field Astr在每次运行开始时初始化为Null。
该表的第一个用途是在字段Avalid中存储Ax和Ay的所有有效值。第二种用途是允许用户选择搜索标准。为此,将表Afull添加为用户搜索表单中的子表单。然后,用户通过在要搜索的值旁边输入任何值> 0到Astr来选择要搜索的Avalid值。之后,将在ORDER BY
然后构建一个sql查询字符串,其目的是返回所有带有任何“排列”的记录。用户选择的Avalid值
我现在已将原始查询缩减为......
SELECT
Main.Ax,
Main.Ay,
(select Astr from Afull where Avalid = Main.Ax) as AxStr
FROM Main
然后添加......
ORDER BY (select Astr from Afull where Avalid = Main.Ax) ASC;
但是我在ORDER BY中遇到语法错误。删除括号没有帮助。
答案 0 :(得分:1)
将整个查询复制到Order by
SELECT main.ax,
main.ay,
(SELECT astr FROM afull WHERE avalid = main.ax) AS AxStr,
(SELECT astr FROM afull WHERE avalid = main.ay) AS AyStr,
Switch(axstr>=0, axstr, axstr<0, 0, Isnull(axstr), 0)
+ Switch(aystr>=0, aystr, aystr<0, 0, Isnull(aystr), 0) AS AStrTotal
FROM main
ORDER BY Switch(axstr>=0, axstr, axstr<0, 0, Isnull(axstr), 0)
+ Switch(aystr>=0, aystr, aystr<0, 0, Isnull(aystr), 0) ASC
或在Sub Select
中使用order by
和outer query
。
SELECT *
FROM (SELECT main.ax,
main.ay,
(SELECT astr FROM afull WHERE avalid = main.ax) AS AxStr,
(SELECT astr FROM afull WHERE avalid = main.ay) AS AyStr,
Switch(axstr>=0, axstr, axstr<0, 0, Isnull(axstr), 0)
+ Switch(aystr>=0, aystr, aystr<0, 0, Isnull(aystr), 0) AS
AStrTotal
FROM main) A
ORDER BY astrtotal ASC
即使Order by 5 Asc
也应该有效
SELECT main.ax,
main.ay,
(SELECT astr FROM afull WHERE avalid = main.ax) AS AxStr,
(SELECT astr FROM afull WHERE avalid = main.ay) AS AyStr,
Switch(axstr>=0, axstr, axstr<0, 0, Isnull(axstr), 0)
+ Switch(aystr>=0, aystr, aystr<0, 0, Isnull(aystr), 0) AS AStrTotal
FROM main
ORDER BY 5 asc