我有一個客戶的需求,他們需要準備以下數據3個值:如何寫SQL查詢與不同的日期爲每列
- 總AMT無償直到30/06/14
- 總AMT從2013年1月4日扣除 - 29/02/2014
- 從2013年1月7日支付總AMT - 29/01/2014
表Transactions
包含以下內容:
支付日期,付款金額,賬戶號碼,僱員
這些可能或可能不會在同一個表,我會弄清楚。但是,每列可能有所不同。如何寫這種複雜的查詢:(可以有人請幫我一個相同類型的例子:
我有一個客戶的需求,他們需要準備以下數據3個值:如何寫SQL查詢與不同的日期爲每列
表Transactions
包含以下內容:
支付日期,付款金額,賬戶號碼,僱員
這些可能或可能不會在同一個表,我會弄清楚。但是,每列可能有所不同。如何寫這種複雜的查詢:(可以有人請幫我一個相同類型的例子:
我不知道如何檢查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
Andreas,非常感謝,對我來說看起來不錯,但是,我需要使用其他邏輯;我的隊友告訴我,它不能在單個查詢中完成,而是在具有不同條件的3列中進行子查詢。對此有何看法?此外,所有這3列都在不同的表中:( – Learner 2015-01-21 04:28:14
我會避免子查詢。加入表使用case語句來從右列中獲取數據https://msdn.microsoft.com/zh-cn/library/ms181765 .aspx – Andreas 2015-01-21 04:48:01
不好意思,我不明白怎麼做,但讓我花一些時間慢慢弄清楚我需要做些什麼:) :)讓你張貼,非常感謝你 – Learner 2015-01-21 04:49:30
沒有一些一些架構信息這個問題是無法回答的 – Andreas 2015-01-21 03:14:48
@Andreas:我已經說了,你可以使用一個示例表有3個不同數量的列,你不能做了? – Learner 2015-01-21 03:17:57
在負面的選民或閉幕者,你有沒有遇到過這種情況?大聲笑 – Learner 2015-01-21 03:18:31