2015-01-21 88 views
-5

我有一个客户的需求,他们需要准备以下数据3个值:如何写SQL查询与不同的日期为每列

  • 总AMT无偿直到30/06/14
  • 总AMT从2013年1月4日扣除 - 29/02/2014
  • 从2013年1月7日支付总AMT - 29/01/2014

Transactions包含以下内容:

支付日期,付款金额,账户号码,雇员

这些可能或可能不会在同一个表,我会弄清楚。但是,每列可能有所不同。如何写这种复杂的查询:(可以有人请帮我一个相同类型的例子:

+1

没有一些一些架构信息这个问题是无法回答的 – Andreas 2015-01-21 03:14:48

+0

@Andreas:我已经说了,你可以使用一个示例表有3个不同数量的列,你不能做了? – Learner 2015-01-21 03:17:57

+0

在负面的选民或闭幕者,你有没有遇到过这种情况?大声笑 – Learner 2015-01-21 03:18:31

回答

1

我不知道如何检查null如果为空,那么另一列,以及相应的列在另一个表

我认为你正在寻找的关键词是“聚结”:

create table othertable(id int primary key identity, usethiscolumnwhennull varchar(255)); 
create table mytable(id int primary key identity, othertable_id int references othertable(id), description varchar(255), thiscolumnissometimesnull varchar(255)); 

insert into othertable(usethiscolumnwhennull) values ('othertable 1'),('othertable 2'); 
insert into mytable(othertable_id,description,thiscolumnissometimesnull) values (1,'no nulls here','mytable 1'),(1,'there is a null! use the value from othertable',null); 

select description, coalesce(m.thiscolumnissometimesnull,o.usethiscolumnwhennull) from mytable m join othertable o on m.othertable_id=o.id 
+0

Andreas,非常感谢,对我来说看起来不错,但是,我需要使用其他逻辑;我的队友告诉我,它不能在单个查询中完成,而是在具有不同条件的3列中进行子查询。对此有何看法?此外,所有这3列都在不同的表中:( – Learner 2015-01-21 04:28:14

+0

我会避免子查询。加入表使用case语句来从右列中获取数据https://msdn.microsoft.com/zh-cn/library/ms181765 .aspx – Andreas 2015-01-21 04:48:01

+0

不好意思,我不明白怎么做,但让我花一些时间慢慢弄清楚我需要做些什么:) :)让你张贴,非常感谢你 – Learner 2015-01-21 04:49:30