如何根据其他表列的表进行排序

时间:2013-09-30 04:27:13

标签: sql-order-by sybase

我有2张桌子

Table 1 
col1  col2
----  ----
BLANK  A
D      A
V      A
BLANK  B
D      B
V      B

Table 2 
col1  col2  sex  age
----  ----  ---- ----
A     as     M    45
A     sa     F    32
A     asd    F    45 
B     as     M    45
B     sa     F    32
B     asd    F    45 

我的输出应该按照表1的col1中的每个值的顺序应该用Table2值重复,并且在顺序和第二个表中它应该按性别和女性记录单独排序我们需要先按年龄划分他们。最后输出表应该如下所示。

COL1  COL2 COL3 SEX AGE
---- ----- ---- --- ---
BLANK  A   as   M   45
BLANK  A   asd  F   45
BLANK  A   sa   F   32
D      A   as   M   45
D      A   asd  F   45
D      A   sa   F   32
V      A   as   M   45
V      A   asd  F   45
V      A   sa   F   32
BLANK  B   as   M   45
BLANK  B   asd  F   45
BLANK  B   sa   F   32
D      B   as   M   45
D      B   asd  F   45
D      B   sa   F   32
V      B   as   M   45
V      B   asd  F   45
V      B   sa   F   32

1 个答案:

答案 0 :(得分:0)

如果你只想要为没有任何连接标准的每个值重复行,那么应该这样做(虽然我没有Sybase来测试,它是相当直接的SQL);

SELECT t1.col1, t1.col2, t2.col2 AS col3, sex, age
FROM Table1 t1, Table2 t2
ORDER BY t1.col1, sex DESC, age DESC  

An SQL Server SQLfiddle as a sample

编辑:在您编辑过的问题之后,我假设您要将t1.col2与相应的t2.col1配对,那么此顺序应该是正确的;

SELECT t1.col1, t1.col2, t2.col2 AS col3, sex, age
FROM Table1 t1
JOIN Table2 t2
  ON t1.col2 = t2.col1
ORDER BY t1.col2, t1.col1, sex DESC, age DESC  

Another SQLfiddle