开发者

SQL Select statement problem

I have the following UNION'd statement:

SELECT  8
UNION ALL
SELECT  7
UNION ALL
SELECT  10

...and a normal SELECT statement:

SELECT column1
  FROM table1

Now my question is, how to merge the two and get the following result

SELECT column1, 10    -- 10 开发者_StackOverflow中文版is the biggest element in the UNION statement
  FROM table1


None are particularly pretty, for the sake of returning a cartesian product:

SELECT t1.column1,
       (SELECT MAX(x.col)
          FROM (SELECT 8 AS col
                UNION ALL
                SELECT 7 AS col
                UNION ALL
                SELECT 10 AS col) x)
 FROM TABLE1 t1

The ANSI-89 approach:

SELECT t1.column1,
       y.max_col
  FROM TABLE1 t1,
       (SELECT MAX(x.col) AS max_col
          FROM (SELECT 8 AS col
                UNION ALL
                SELECT 7 AS col
                UNION ALL
                SELECT 10 AS col) x) y

The ANSI-92 approach, using CROSS JOIN (not supported on all databases):

    SELECT t1.column1,
           y.max_col
      FROM TABLE1 t1
CROSS JOIN (SELECT MAX(x.col) AS max_col
              FROM (SELECT 8 AS col
                    UNION ALL
                    SELECT 7 AS col
                    UNION ALL
                    SELECT 10 AS col) x) y


What about

SELECT column1, (SELECT MAX(v) FROM (SELECT  8 AS v
                                     UNION ALL
                                     SELECT  7 AS v
                                     UNION ALL
                                     SELECT  10 AS v
                                     ) x)
FROM   table1

?


SELECT column1, (SELECT MAX(TABLE2.X) 
        FROM (SELECT  8 AS X UNION ALL SELECT  7 AS X UNION ALL SELECT  10 AS X) TABLE2 ) 
     AS MY_MAX
FROM TABLE1
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜