0

我有一个包含两列的表格,例如三行,如上所示。然后我想在这张桌子上创建一个视图。

此视图应为表格中的每一行显示与该行中所写的行数一样多的行。

我不知道如何解决这个问题,有人举例说明如何使用 TSQL 构建视图?

例子:

在此处输入图像描述

4

4 回答 4

3

您可以使用递归 CTE 来拆分值,类似于:

;WITH CTE AS
(
    SELECT name, value
    FROM YourTable
    UNION ALL 
    SELECT name, value-1
    FROM CTE
    WHERE value-1 >= 1
)
SELECT t.name, t.value
FROM yourtable t
inner join CTE c
  on t.name = c.name
ORDER BY name, value
OPTION(MAXRECURSION 0)

请参阅带有演示的 SQL Fiddle

结果是:

|  NAME | VALUE |
-----------------
|  milk |     4 |
|  milk |     4 |
|  milk |     4 |
|  milk |     4 |
| sugar |     2 |
| sugar |     2 |
|   tea |     7 |
|   tea |     7 |
|   tea |     7 |
|   tea |     7 |
|   tea |     7 |
|   tea |     7 |
|   tea |     7 |
于 2013-01-15T11:26:01.010 回答
2

您应该将此表与一些具有 1、2、3、4、5、6、.... 数字的字段的表连接起来。例如:

SQLFiddle 演示

with t0 as 
( select 1 n
  union all
  select 2 n
  union all 
  select 3 n 
 ),
tCount as
(select ROW_number() over (order by t1.n) rn
from t0,
     t0 as t1,
     t0 as t2,
     t0 as t3,
     t0 as t4
)
select t.* from t
join tCount on t.Number>=tCount.rn
order by name
于 2013-01-15T11:22:07.677 回答
2
WITH    q(n) AS
        (
        SELECT  1
        UNION ALL
        SELECT  n + 1
        FROM    q
        WHERE   n <
                (
                SELECT  MAX(repeats)
                FROM    mytable
                )
        )
SELECT  t.*
FROM    mytable t
JOIN    q
ON      q.n <= t.repeats
于 2013-01-15T11:23:42.067 回答
0

请检查

;WITH T AS(
    SELECT 
        COl1, Col2, 1 AS NUM 
    FROM TableName

    UNION ALL

    SELECT 
        T1.COl1, T1.Col2, T.NUM+1 AS NUM 
    FROM TableName T1 INNER JOIN T ON T1.Col1=T.Col1
    WHERE T.NUM+1<=T1.Col2
)
SELECT COl1, Col2 FROM T ORDER BY COl1
于 2013-01-15T11:27:19.790 回答