在SQL Server中将列设置为具有值的侦听器
我有两个表作为类别和子类别连接 这是我的桌子在SQL Server中将列设置为具有值的侦听器,sql,sql-server,Sql,Sql Server,我有两个表作为类别和子类别连接 这是我的桌子 ---------------------- Values | Category ---------------------- red | Color blue | Color green | Color male | Gender female | Gender singe | Status married | status 有可能是这样吗 ----------------------------
----------------------
Values | Category
----------------------
red | Color
blue | Color
green | Color
male | Gender
female | Gender
singe | Status
married | status
有可能是这样吗
---------------------------------
Color | Status | Gender
---------------------------------
red | single | male
blue | married | female
green | |
此外,当我添加另一个类别(如payment\u type
)时,我会自动添加为标题
看起来像这样
----------------------------------------------------
Color | Status | Gender | Payment Type
---------------------------------------------------
red | single | male |
blue | married | female |
green | | |
我不知道从哪里开始这个问题,但我希望有人能帮助我
提前感谢您可以使用
行号()
执行聚合:
select max(case when cat = 'color' then val end) as color,
max(case when cat = 'status' then val end) as status,
max(case when cat = 'Gender' then val end) as Gender,
max(case when cat = 'payment_type' then val end) as payment_type
from (select t.*, row_number() over (partition by cat order by val) as seq
from table t
) t
group by seq;
注意:如果类别
不会增加太多,那么您可以使用此方法,否则您可以使用动态透视
和行号()
使用透视
;WITH CTE ([Values],Category,[Payment Type])
AS
(
SELECT 'red' , 'Color' ,NULL
UNION ALL SELECT 'blue' , 'Color' ,NULL
UNION ALL SELECT 'green' , 'Color' ,NULL
UNION ALL SELECT 'male' , 'Gender' ,NULL
UNION ALL SELECT 'female' , 'Gender' ,NULL
UNION ALL SELECT 'single' , 'Status',NULL
UNION ALL SELECT 'married' , 'status' ,NULL
)
SELECT [Color],[Gender],[Status],[Payment Type]
FROM
(
SELECT *
, ROW_NUMBER()OVER(PARTITION BY Category ORDER BY [Values]) AS Seq
FROM CTE o
) AS Src
PIVOT
(
MAX([Values]) FOR Category IN ([Color],[Gender],[Status],[Payment Type])
)pvt
结果
Color Gender Status Payment Type
----------------------------------------
blue female married NULL
green male single NULL
red NULL NULL NULL
SQL查询返回固定数量的列,因此无法通过简单查询满足最后一个要求。您需要动态SQL。请尝试此操作。我会告诉你结果。但是当我添加一个新的类别时呢。我还需要另一个查询吗?我将尝试此查询。将更新结果。还将搜索动态轴,因为类别和子类别很可能会增加。