根据输入数据生成系列

时间:2017-06-22 05:15:58

标签: sql sql-server tsql

declare @set varchar(50)
set @set = '1,4,2'

输出: -

    1,1,1  
    1,2,1  
    1,3,1  
    1,4,1  
    1,1,2  
    1,2,2       
    1,3,2  
    1,4,2  

2 个答案:

答案 0 :(得分:2)

以下是使用Number表和Parsename函数

的一个技巧
DECLARE @set varchar(50)
SET @set = replace(reverse('1,4,2'),',','.')

;WITH lv0 AS (SELECT 0 g UNION ALL SELECT 0)
    ,lv1 AS (SELECT 0 g FROM lv0 a CROSS JOIN lv0 b) -- 4
    ,lv2 AS (SELECT 0 g FROM lv1 a CROSS JOIN lv1 b) -- 16
    ,lv3 AS (SELECT 0 g FROM lv2 a CROSS JOIN lv2 b) -- 256
    ,Tally (n) AS (SELECT ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM lv3),
    fst as (SELECT col1 = n FROM Tally where n <= parsename(@set,1)),
    scd as (SELECT col2 = n FROM Tally where n <= parsename(@set,2)),
    thd as (SELECT col3 = n FROM Tally where n <= parsename(@set,3))
SELECT *
FROM   fst
        LEFT JOIN scd ON 1 = 1
        LEFT JOIN thd ON 1 = 1
ORDER  BY col1,col3,col2 

如果需要,您可以通过添加更多CTE 来堆叠CROSS JOIN's来增加数字

结果:

╔══════╦══════╦══════╗
║ col1 ║ col2 ║ col3 ║
╠══════╬══════╬══════╣
║    1 ║    1 ║    1 ║
║    1 ║    2 ║    1 ║
║    1 ║    3 ║    1 ║
║    1 ║    4 ║    1 ║
║    1 ║    1 ║    2 ║
║    1 ║    2 ║    2 ║
║    1 ║    3 ║    2 ║
║    1 ║    4 ║    2 ║
╚══════╩══════╩══════╝

有关Numbers表的更多信息

boolean indexing

Tally Tables in T-SQL

答案 1 :(得分:1)

这是一个使用递归CTE构建带有数字的Tally表的解决方案。
因此,最大数量不是固定的。

然后它将集合中的数字加入到它们中。

使用concat生成集合。

Sets
-----
1,1,1
1,2,1
1,3,1
1,4,1
1,1,2
1,2,2
1,3,2
1,4,2

<强>返回:

N AS (select n from (values (1),(2),(3),(4),(5),(6),(7),(8),(9)) v(n))

如果@set只有2个数字,那么它仍然可以工作(注意n3上的左连接)

如果您确定这些数字不超过9,那么您可以通过用值列表替换递归CTE来简化查询。
例如:

    public function index()
    {
      return view('backend.bookings'/*, ['bookingDetails' => $bookings]*/);
    }

    public function dataTables(Request $request)
    {
        $bookings = Booking::where('is_delete', 0)
            ->get();

        // Functionality for laravel datatables
        $bookingDetails = Datatables::collection($bookings)
            ->addColumn('action', function ($bookings) {
                return '<a href="/bookings/'.$bookings->_id.'" class="btn btn-xs btn-danger deleteEvent" data-id="'.$bookings->_id.'"><i class="glyphicon glyphicon-trash"></i> Delete</a>';
            })
            ->make(true);

        return $bookingDetails;
    }