我有两张表PAY
和INVO
,我希望在一个表格中显示我也按日期排序
答案 0 :(得分:0)
首先将数据插入到临时表中,并按日期升序排列 使用以下CTE方法获得结果:
CREATE TABLE #Invoice(Name VARCHAR(100),_Date DATE,total INT)
CREATE TABLE #pay(Name VARCHAR(100),_PayDate DATE,_money INT)
CREATE TABLE #Balance(Id INT IDENTITY(1,1),Name VARCHAR(100),_PayDate
DATE,DE INT ,CR INT ,Bal INT)
INSERT INTO #Invoice(Name ,_Date ,total )
SELECT 'mark','03/01/2015',200 UNION ALL
SELECT 'mark','01/02/2016',150 UNION ALL
SELECT 'mark','01/02/2017',200
INSERT INTO #pay(Name ,_PayDate ,_money )
SELECT 'mark','01/01/2016',100 UNION ALL
SELECT 'mark','01/01/2017',200
INSERT INTO #Balance ( Name ,_PayDate ,DE , CR)
SELECT Name , _Date Date , total , 0
FROM #Invoice
UNION ALL
SELECT Name , _PayDate Date , 0 , _money
FROM #pay
ORDER BY Date ASC
;WITH CTEBalence(_Id , Name ,_PayDate ,DE , CR ,bal) AS
(
SELECT Id , Name ,_PayDate ,DE , CR , CASE WHEN DE > 0 THEN DE WHEN CR > 0
THEN CR END
FROM #Balance
WHERE Id = 1
UNION ALL
SELECT Id ,B.Name ,B._PayDate ,B.DE , B.CR , CASE WHEN B.DE > 0 THEN (
C.bal + B.DE ) WHEN B.CR > 0 THEN ( C.bal - B.CR ) END
FROM #Balance B
JOIN CTEBalence C ON Id > _Id AND _Id = Id - 1
)
SELECT * FROM CTEBalence
答案 1 :(得分:0)
假设数据库是Oracle。您可以使用Oracle的分析函数SUM来实现所需的结果。
以下是基于所提供数据的解决方案。
create table pay
(
name varchar(10),
"date" date,
money number
);
create table invo
(
name varchar(10),
"date" date,
invo_total number
);
insert into pay values ('mark',to_date('01012016','mmddyyyy'),100);
insert into pay values ('mark',to_date('01012017','mmddyyyy'),200);
select * from pay;
NAME日期MONEY
---------- --------- ----------
标记01-JAN-16 100
标记01-JAN-17 200
insert into invo values ('mark',to_date('03012015','mmddyyyy'),200);
insert into invo values ('mark',to_date('02012016','mmddyyyy'),150);
insert into invo values ('mark',to_date('01022017','mmddyyyy'),200);
select * from invo;
姓名日期INVO_TOTAL
---------- --------- ----------
标记01-MAR-15 200
标记01-FEB-16 150
标记01-FEB-17 200
WITH trans_dtls AS
(
SELECT rownum rn,
name,
"date",
NVL(i.invo_total,0) de,
NVL(p.money,0) cr,
NVL(i.invo_total,0)- NVL(p.money,0) AS curr_sum
FROM pay p
FULL OUTER JOIN invo i USING (name,"date")
ORDER BY name,"date"
)
SELECT
td1.name,
td1."date",
de,
cr,
SUM(td1.curr_sum) over (order by td1.name,"date") bal
FROM trans_dtls td1;
姓名日期DE CR BAL
---------- --------- ---------- ---------- ------- ---
标记01-MAR-15 200 0 200
标记01-JAN-16 0 100 100
标记01-FEB-16 150 0 250
标记01-JAN-17 0 200 50
标记01-FEB-17 200 0 250