我在table1
中有这些列:
现在,我需要添加虚拟月份。如何快速编写SQL查询,将Q1(作为一行)除以3个月?
结果应该是这样的:
这可能吗?
编辑1 :
这是生成第一个表
的SQL语句select year, time, q, th, l1, l2, par, par2, sum(value)
from table1
group by year, time, q, th, l1, l2, par, par2
答案 0 :(得分:3)
使用CROSS JOIN
和ROW_NUMBER()
尝试此方法。
CROSS JOIN
将在主表的每个季度输出3行,然后使用ROW_NUMBER()
函数获取每季度的季数
以下是一个例子。
--Add some sample data to represent your table1
DECLARE @table1 TABLE ([Year] int, Q varchar(10))
INSERT INTO @table1 ([Year], Q)
VALUES (2016, 'Q1'),
(2016, 'Q2'),
(2016, 'Q3'),
(2016, 'Q4')
--Query
SELECT [year], Q,
ROW_NUMBER() OVER (PARTITION BY [Year] ORDER BY qtr) [Month]
FROM @Table1 t1
CROSS JOIN (SELECT qtr FROM (VALUES(1),(2),(3)) Table2 (qtr)) t2
答案 1 :(得分:1)
使用convert
将Q1,Q2,Q3,Q4变为开始月份数;然后使用union
将行复制三次(将总和除以三)。
select year, time, q,
month = convert(int, right(q,1))*3 - 2,
th, l1, l2, par, par2, sum(value)/3
from table1 group by year, time, q, th, l1, l2, par, par2
union all
select year, time, q,
month = convert(int, right(q,1))*3 - 1,
th, l1, l2, par, par2, sum(value)/3
from table1 group by year, time, q, th, l1, l2, par, par2
union all
select year, time, q,
month = convert(int, right(q,1))*3,
th, l1, l2, par, par2, sum(value)/3
from table1 group by year, time, q, th, l1, l2, par, par2
答案 2 :(得分:0)
这不是你要求的,但你可以知道如何在你的情况下采用它。我使用表变量你必须用你的表名替换它。我做了一些插入只是为了测试目的:
declare @table table (Q varchar(10),amount decimal(18,2))
insert into @table values ('Q1',80000),('Q2',500000),('Q3',457000),('Q4',75000)
declare @table2 table (Q varchar(10),muaji int)
insert into @table2 values ('Q1',1),('Q1',2),('Q1',3),('Q2',4),('Q2',5),('Q2',6),('Q3',7),('Q3',8),('Q3',9),('Q4',10),('Q4',11),('Q4',12)
select t1.Q,t2.muaji,t1.amount/3 from @table t1 inner join @table2 t2 on t1.Q=t2.Q
答案 3 :(得分:0)
这应该有效:
declare @t table (id int identity(1,1),q char(2))
insert into @t
select 'q1'
union all select 'q1'
union all select 'q2'
union all select 'q2'
union all select 'q2'
union all select 'q1'
union all select 'q4'
union all select 'q3'
union all select 'q3'
union all select 'q4'
union all select 'q4'
union all select 'q3'
--select * from @t
select mn = ROW_NUMBER() OVER(ORDER BY q) ,q
from @t