我是sql server的新手。
如何显示记录开仓和关闭股票?
我不知道如何在SQL Server查询中显示记录表Formate?
请帮帮我
我的表
Ttype ItemName TDate DC Qty
LGR VANILA 08-04-2018 C 10
GRN VANILA 08-04-2018 C 10
GRN VANILA 09-04-2018 C 20
DA VANILA 10-04-2018 D 10
DA VANILA 10-04-2018 D 10
GRN VANILA 11-04-2018 C 10
DA VANILA 12-04-2018 D 10
开始日期:11-04-2018结束日期:12-04-2018
预期输出
Ttype ItemName TDate DC Qty
Op.St VANILA 11-04-2018 C 20
GRN VANILA 11-04-2018 C 10
DA VANILA 12-04-2018 D 10
Cl.St VANILA 12-04-2018 C 20
答案 0 :(得分:1)
lead()
lag()
和union all
;with cte as (
select 1 as Sort, 'Op.St' Ttype, null ItemName, null TDate, null DC, null Qty union all
select 2 as Sort, Ttype, ItemName, TDate, DC, Qty from table t
where tdate >= '20180411' and tdate <= '20180412' union all
select 3 as Sort, 'Cl.St' Ttype, null ItemName, null TDate, null DC, null Qty
)
select Ttype,
case (sort) when 1 then lead(ItemName) over (order by sort)
when 3 then lag(ItemName) over (order by sort) else ItemName end ItemName ,
case (sort) when 1 then lead(TDate) over (order by sort)
when 3 then lag(TDate) over (order by sort) else TDate end TDate,
case (sort) when 1 then lead(DC) over (order by sort)
when 3 then lag(DC) over (order by sort) else DC end DC,
case when sort <> 2 then (select sum(Qty) from cte c) else Qty end Qty
from cte c
函数对我来说有点头疼
open(FILE , "filename");
while ( < FILE > ){
}
答案 1 :(得分:1)
作为变体,您可以使用UNION ALL
DECLARE
@StartDate date='20180411',
@EndDate date='20180412'
SELECT
1 RowType,
'Op.St' Ttype,
ItemName,
@StartDate TDate,
IIF(SUM(IIF(DC='D',1,-1)*Qty)<0,'C','D') DC,
ABS(SUM(IIF(DC='D',1,-1)*Qty)) Qty
FROM MyTable
WHERE TDate<@StartDate
GROUP BY ItemName
UNION ALL
SELECT
2 RowType,
Ttype,
ItemName,
TDate,
DC,
Qty
FROM MyTable
WHERE TDate BETWEEN @StartDate AND @EndDate
UNION ALL
SELECT
3 RowType,
'Cl.St' Ttype,
ItemName,
@EndDate TDate,
IIF(SUM(IIF(DC='D',1,-1)*Qty)<0,'C','D') DC,
ABS(SUM(IIF(DC='D',1,-1)*Qty)) Qty
FROM MyTable
WHERE TDate<=@EndDate
GROUP BY ItemName
ORDER BY RowType,TDate
我认为这种方式很清楚。
SQL小提琴 - http://www.sqlfiddle.com/#!18/ec687/1
另一个变种
DECLARE
@StartDate date='20180411',
@EndDate date='20180422'
SELECT
1 RowType,
'Op.St' Ttype,
d.ItemName,
m.TDate,
IIF(d.Qty<0,'C','D') DC,
ABS(d.Qty) Qty
FROM (SELECT @StartDate TDate) m
OUTER APPLY
(
SELECT ItemName,SUM(IIF(DC='D',1,-1)*Qty) Qty
FROM MyTable
WHERE TDate<m.TDate
GROUP BY ItemName
) d
UNION ALL
SELECT
2 RowType,
Ttype,
ItemName,
TDate,
DC,
Qty
FROM MyTable
WHERE TDate BETWEEN @StartDate AND @EndDate
UNION ALL
SELECT
3 RowType,
'Cl.St' Ttype,
d.ItemName,
m.TDate,
IIF(d.Qty<0,'C','D') DC,
ABS(d.Qty) Qty
FROM (SELECT @EndDate TDate) m
OUTER APPLY
(
SELECT ItemName,SUM(IIF(DC='D',1,-1)*Qty) Qty
FROM MyTable
WHERE TDate<=m.TDate
GROUP BY ItemName
) d
ORDER BY RowType,TDate
如果您想要获得行Op.St
和Cl.St
,可以使用第二种变体(例如,您可以设置@StartDate='20180401'
和@EndDate='20180422'
)