SQL表作为矩阵(T-SQL)

时间:2015-05-13 08:20:06

标签: sql sql-server tsql select matrix

我有一些有趣的复杂谜题,至少对我来说很复杂。 所以这就是问题......

我有一个看起来像这样的简单表

Create table User(UserID int, DaysCount int, Date int) 

然后我有一个简单的选择,基于DaysCount给用户一些从1到4的特定等级,并将其添加到一些临时表。

Select UserID, 
(case
when DaysCount >= 0 and DaysCount <= 10 then 1
when DaysCount >= 11 and DaysCount <= 20 then 2
when DaysCount >= 21 and DaysCount <= 30 then 3
when DaysCount >= 31 and DaysCount <= 40 then 4
end) as Grade, Month
Into #A
from Users
where Date = 20150131

Select UserID, 
(case
when DaysCount >= 0 and DaysCount <= 10 then 1
when DaysCount >= 11 and DaysCount <= 20 then 2
when DaysCount >= 21 and DaysCount <= 30 then 3
when DaysCount >= 31 and DaysCount <= 40 then 4
end) as Grade, Month
Into #B
from Users
where Date = 20150228

然后这是一个复杂的部分,我很难...我需要做一个将从temp中选择的查询。表并将数据插入新表(此表需要看起来像矩阵),它看起来像这样。

      Here is how table should look at end

 UserID      1    2    3     4          Date

   11        1    0    0     0        20150131  
   11        0    0    1     0        20150228
   13        0    1    0     0        20150228
   14        0    0    0     1        20150131  

感谢您的帮助,如果您不明白我的问题,请告诉我们!

2 个答案:

答案 0 :(得分:3)

除非我遗漏了某些内容,否则所有临时表都不是必需的,您只需将其作为单个查询从users表中提取,而不是使用返回1和1之间的值的单个case表达式。 4,使用返回1或0的4个case表达式:

SELECT  UserID,
        [1] = CASE WHEN DaysCount >= 0 AND DaysCount <= 10 THEN 1 ELSE 0 END,
        [2] = CASE WHEN DaysCount >= 11 AND DaysCount <= 20 THEN 1 ELSE 0 END,
        [3] = CASE WHEN DaysCount >= 21 AND DaysCount <= 30 THEN 1 ELSE 0 END,
        [4] = CASE WHEN DaysCount >= 31 AND DaysCount <= 40 THEN 1 ELSE 0 END,
        Date 
FROM    Users
WHERE   Date IN ('20150131', '20150228');

或者如果您更喜欢更传统的列别名:

SELECT  UserID,
        CASE WHEN DaysCount >= 0 AND DaysCount <= 10 THEN 1 ELSE 0 END AS [1],
        CASE WHEN DaysCount >= 11 AND DaysCount <= 20 THEN 1 ELSE 0 END AS [2],
        CASE WHEN DaysCount >= 21 AND DaysCount <= 30 THEN 1 ELSE 0 END AS [3],
        CASE WHEN DaysCount >= 31 AND DaysCount <= 40 THEN 1 ELSE 0 END AS [4],
        Date 
FROM    Users
WHERE   Date IN ('20150131', '20150228');

答案 1 :(得分:0)

由于它们是10的间隔,因此这是一种较短的写入方式。

SELECT  DaysCount, 
        [1] = CASE WHEN dcID <= 1 THEN 1 ELSE 0 END,
        [2] = CASE WHEN dcID  = 2 THEN 1 ELSE 0 END,
        [3] = CASE WHEN dcID  = 3 THEN 1 ELSE 0 END,
        [4] = CASE WHEN dcID  = 4 THEN 1 ELSE 0 END
FROM Users
CROSS APPLY (SELECT CEILING(DaysCount/10.0)) CA(dcID)
WHERE [Date] IN ('20150131', '20150228');