小编典典

从表中选择“记录多次”

sql

我有一个这样的SQL语句:

编辑 :

SELECT 
    location as Location 
FROM
    Table1 
WHERE 
    OnsiteOffshore = 'Offshore' AND Acc_Code = 'ABC'

UNION

SELECT 
    Country 
FROM 
    Table1 
WHERE
    OnsiteOffshore = 'Onsite' AND Acc_Code = 'ABC'

此SQL查询给出以下结果:

Chennai
Bangalore
USA
NewZealand

但是由于某些要求,我需要这样的输出:

Chennai
Chennai
Chennai
Chennai
Bangalore
Bangalore
Bangalore
Bangalore
USA
USA
USA
USA
NewZealand
NewZealand
NewZealand
NewZealand

意思是说每个位置需要输出4次。

请帮助如何获得相同的。


阅读 182

收藏
2021-03-10

共1个答案

小编典典

SELECT Location 
FROM Table1
  CROSS JOIN
    ( VALUES (1),(2),(3),(4)
    ) AS four(dummy)

如果4不是一个常数,而是(如@xQbert指出/要求的)是表的行数,则可以使用以下命令:

SELECT a.Location 
FROM Table1 AS a
  CROSS JOIN
     Table1 AS b

如果没有Table1任何查询(但是很复杂),则可以将其用于4个副本:

SELECT Location 
FROM (
       SELECT Location       --- complex query here
       ...                   --- inside parenthesis
     UNION 
       SELECT Country
       ...
     ) AS Table1
  CROSS JOIN
    ( VALUES (1),(2),(3),(4)
    ) AS four(dummy)

或此n副本:

WITH cte AS
  ( SELECT Location       --- complex query here
    ...                   --- inside parenthesis
    UNION 
    SELECT Country
    ...
  )
SELECT a.Location 
FROM cte AS a
  CROSS JOIN
     cte AS b
2021-03-10