SQL 表作为矩阵 (T-SQL)

标签 sql sql-server t-sql 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  

感谢您的帮助,如果您不明白我的问题到底是什么,请告诉我!

最佳答案

除非我遗漏了某些内容,否则所有临时表都是不必要的,您可以简单地从 users 表中将其提取为单个查询,而不是使用返回值的单例表达式在 1 和 4 之间,使用 4 个返回 1 或 0 的 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');

关于SQL 表作为矩阵 (T-SQL),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30209371/

相关文章:

php - 我的mysql语法有错误

c# - 插入记录后如何从SQL Server获取标识值

c# - 将搜索字符串转换为与全文兼容的搜索字符串?

SQL Server 分组

mysql - 优化此 MySQL 查询,删除另一个表中缺少的行

sql - 多个 SQL 连接

sql-server - 在基于分级的税收系统中计算税收的情况

sql-server - 在sql server中将数据从一个表传输到另一个表

php - 友谊系统SQL结构与查询

.net - 为什么在建立与 SQL Server 的连接时会发生与网络相关或特定于实例的错误?