帮助SQL查询。 [英] Help with a SQL query.
本文介绍了帮助SQL查询。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要一个查询,其中
a特定列值在特定日期需要,而其他一些列值在两个日期之间是必需的
例如
选择 t1.col1,t2.col2,SUM(col3)
来自 my_table1 内部 join my_table2 on t1.id = t2.id
其中 [日期 ] ' 2014-01-01' 和 ' 2014-02-11'
group by t1.col1,t2.col2
现在,我需要另一个列,即col4,它只需要特定的列date
即如果我要写一个单独的查询,它将是:
选择 t2.col4 来自 my_table1 内部 join my_table2 on t1.id = t2.id
where [日期] = ' 2014-02-11 '
有没有什么方法可以使用单个查询实现这两个?
任何帮助都将非常感激。
解决方案
你可以用CTE来轻松实现它。
我这样做:
选择t1.col1,t2.col2,SUM(col3),
case [Date] ='2014-02-11'然后col4 else NULL结束
来自my_table1内部联接my_table2 on t1.id = t2.id
where [Date]在'2014-01-01'和'2014-02-11'
group by t1.col1,t2.col2之间,[Date] ='2014-02-11'然后col4 else NULL结束
I need a query where
a particular column value is required as of a particular date whereas some of the other column values are required as of between two dates
e.g.
select t1.col1, t2.col2, SUM(col3)
from my_table1 inner join my_table2 on t1.id = t2.id
where [Date] between '2014-01-01' and '2014-02-11'
group by t1.col1, t2.col2
Now, I need another column i.e. col4 which required only as of a particular date
i.e. if I were to write a separate query it would be :
select t2.col4 from my_table1 inner join my_table2 on t1.id = t2.id
where [Date] = '2014-02-11'
Is there any way both of these could be achieved using a single query?
Any help would be much appreciated.
解决方案
you can use CTE with this to achieve it easily.
I'd do it like this:
select t1.col1, t2.col2, SUM(col3), case when [Date] = '2014-02-11' then col4 else NULL end from my_table1 inner join my_table2 on t1.id = t2.id where [Date] between '2014-01-01' and '2014-02-11' group by t1.col1, t2.col2, case when [Date] = '2014-02-11' then col4 else NULL end
这篇关于帮助SQL查询。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文