TSQL-View:如何对表的行进行乘法运算

时间:2013-01-15 11:08:02

标签: sql tsql view

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

此视图应该为表格中的每一行显示与此行中写入的行数相同的行。

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

示例:

enter image description here

4 个答案:

答案 0 :(得分: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 with Demo

结果是:

|  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 |

答案 1 :(得分:2)

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

SQLFiddle demo

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

答案 2 :(得分: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

答案 3 :(得分: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