【问题标题】:How to duplicate columns data in SQL Server 2008?如何在 SQL Server 2008 中复制列数据?
【发布时间】:2017-05-28 13:24:47
【问题描述】:

这是我的查询:

select 
    t.range as [score range], count(*) as [number of occurences]
from 
    (select 
         case 
            when answer_count between 0 and 5 then ' 0- 9'
            when answer_count between 5 and 10 then '10-19'
            else '20-99' end as range
     from 
         points 
     where 
         type = 'product_quiz') t 
group by 
    t.range

输出是:

/-------------------------------------\
| score range | number of occurrences |
|-------------+-----------------------|
|   10-19     |         121327        |
|    0- 9     |         129195        |
\-------------------------------------/

但我想要这样的输出:

/-----------------------------------------------------------------------------\
| score_range | number_of_occurrences | score_range1 | number_of_occurrences1 |
|-------------+-----------------------+--------------+------------------------|
|   10-19     |         121327        |    10-19     |         121327         |
|    0- 9     |         129195        |     0- 9     |         129195         |
\-----------------------------------------------------------------------------/

如何使用子查询来实现这一点?

【问题讨论】:

  • 如果你想要那个输出,你将需要旋转。但是为什么不将每个不同的范围作为单独的列呢?
  • 为什么需要子查询?这似乎会增加不必要的复杂性和额外的处理开销。您可以通过select t.range as [score_range], count(*) as [number_of_occurences], t.range as [score_range1], count(*) as [number_of_occurences1] from ... 之类的方式实现您想要的
  • 但这里我的要求是这样使用..如果可能在 pivot 中那么它是很好的。

标签: sql sql-server-2008 tsql select


【解决方案1】:

如果我理解正确,您不需要子查询(除非您指的是 FROM 子句中已经存在的子查询):

select 
    t.range as [score_range], 
    count(*) as [number_of_occurences],
    t.range as [score_range1], 
    count(*) as [number_of_occurences1]
from 
    (select 
         case 
            when answer_count between 0 and 5 then ' 0- 9'
            when answer_count between 5 and 10 then '10-19'
            else '20-99' end as range
     from 
         points 
     where 
         type = 'product_quiz') t 
group by 
    t.range

为什么你会想要这样做(以及为什么你会特别想要使用子查询)是另一个问题。

【讨论】:

  • 感谢您的意见。但我的要求是,我想为 number_of_occurences 和 number_of_occurences1 列添加子查询,以防万一
  • 这个答案能解决你的问题吗?如果没有,请告诉我们还有什么问题,我们可以为您提供更好的答案。
  • 没有。例如:我想要这样的查询 select t.range as [score_range], (select count () from tablename )as [number_of_occurences], (select count () from tablename1 )as [number_of_occurences1],从(当 answer_count 介于 0 和 5 之间时选择案例,然后是 '0-9' 当 answer_count 在 5 和 10 之间然后是 '10-19' 否则 '20-99' 以类型 = 'product_quiz' 的点的范围结束) t group by t .range 我想要这样
  • 你为什么要这样?我在这个答案中给出的内容会在您的问题中产生所需的输出,所以我们中的一个人在某处遗漏了一些东西......
猜你喜欢
  • 2014-12-30
  • 1970-01-01
  • 1970-01-01
  • 2013-12-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多