sql-server-2008 – 在T-SQL中分解2列以上的表

前端之家收集整理的这篇文章主要介绍了sql-server-2008 – 在T-SQL中分解2列以上的表前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
如果我有下表
Hour    Clicks  Conversions
12:00   2   0
1:00    3   2
2:00    1   1

如何编写一个SELECT语句,在两列中分解它,所以我得到:

12:00   1   0
12:00   1   0
1:00    1   0
1:00    1   1
1:00    1   1
2:00    1   1

如果我不能用SELECT做到这一点,我如何用循环编写存储过程?

谢谢!

解决方法

这假设对于[Hour]的任何给定值,将只有一行.如果可能存在重复,我会首先聚合它们(我假设源已经是某种聚合).
DECLARE @x TABLE ([Hour] CHAR(5),Clicks INT,Conversions INT);

INSERT @x SELECT '12:00',2,0
UNION ALL SELECT '13:00',3,2
UNION ALL SELECT '14:00',1,1;

;WITH x AS
(
    SELECT n = ROW_NUMBER() OVER (ORDER BY s1.[object_id]) FROM sys.all_columns AS s1
    -- CROSS JOIN (SELECT 1 UNION ALL SELECT 2) AS s2 -- to double the rows if you need more
),y AS 
(
    SELECT [Hour],Conversions,Clicks,m = MAX(CASE WHEN Conversions > Clicks THEN Conversions ELSE Clicks END) 
    FROM @x GROUP BY [Hour],Clicks
)
SELECT y.[Hour],Clicks = CASE WHEN Clicks < x.n THEN 0 ELSE 1 END,Conversions = CASE WHEN Conversions < x.n THEN 0 ELSE 1 END
FROM x INNER JOIN y ON x.n <= y.m
ORDER BY CONVERT(TIME,y.[Hour]),Conversions;
原文链接:https://www.f2er.com/mssql/77100.html

猜你在找的MsSQL相关文章