在SQL

时间:2019-01-29 09:39:03

标签: sql sql-server

我的新数据来自源头grouped by,因此是否有任何代码可以细分或取消分组数据,然后根据分组的列来分配其值。

桌子看起来像这样

| age | education | city | male | female

| 28  | Secondary |  x   |  0   |   2
| 28  | University|  x   |  1   |   2
| 29  | Primary   |  y   |  1   |   0

我希望代码执行类似的操作

| age | education | city | gender |

| 28  | Secondary |  x   | female |
| 28  | Secondary |  x   | female | 
| 28  | University|  x   |  male  |
| 28  | University|  x   | female |
| 28  | University|  x   | female |
| 29  | Primary   |  y   |  male  |

4 个答案:

答案 0 :(得分:2)

您要使用APPLY递归 CTE

with cte as (
     select age, education, city, mf, gender, 1 as val
     from table t cross apply
          ( values (male, 'male'), (female, 'female')
          ) tt (mf, gender)
     where mf > 0
     union all
     select age, education, city, mf, gender, val + 1
     from cte c
     where mf > val
)

select age, education, city, gender 
from cte c
order by age, education, city;

默认情况下,它具有100递归级别,如果您具有更高的性别递归,则可能需要使用option (maxrecursion 0)

答案 1 :(得分:2)

简单的方法是将UNION ALLCROSS APPLY

SELECT M.age,education,city,'Male' as Gender
FROM #TAB M
CROSS APPLY
(
    SELECT * FROM MASTER..SPT_VALUES WHERE TYPE = 'P' AND NUMBER BETWEEN 1 AND M.MALE
)MALE

UNION ALL

SELECT F.age,education,city,'Female' as Gender
FROM #TAB F
CROSS APPLY
(
    SELECT * FROM MASTER..SPT_VALUES WHERE TYPE = 'P' AND NUMBER BETWEEN 1 AND F.FEMALE
)MALE

答案 2 :(得分:0)

UNPIVOT和一个数字表将您带到那里。我模拟了一个非常基本的数字表,这里只有两行,以使查询自包含:

declare @t table (age int,education varchar(15),city char(1),male int,female int)
insert into @t(age , education , city , male , female) values
(28,'Secondary','x',0,2),
(28,'University','x',1,2),
(29,'Primary','y',1,0)

;With UP as (
    select
        *
    from
        @t
            unpivot (cnt  for gender in (male,female)) p
), Numbers(n) as (
    select 1 union all select 2
)
select *
from UP inner join Numbers on n <= cnt

结果(您可以在最后的SELECT中轻松删除几个额外的列):

age         education       city cnt         gender     n
----------- --------------- ---- ----------- ---------- -----------
28          Secondary       x    2           female     1
28          Secondary       x    2           female     2
28          University      x    1           male       1
28          University      x    2           female     1
28          University      x    2           female     2
29          Primary         y    1           male       1

(如果您有一个实数表,并且包含0或负数,则需要在联接中使用其他过滤器)

答案 3 :(得分:-1)

您应该使用存储过程在第一个表上循环,并在另一个表上插入记录

<html>
...
<body>

<div id="1"></div>
<div id="content">

  <html><head></head><bod>another website content</body></html>

</div>
</body>