1

我的桌子是这样的

SlNo    Date                 Session    MemberCode  Litres  Fat     Price   Amount  GS     Col1   Col
16   2013-07-02 16:27:17.000    E           0        1.00   0.00    28.00   28.00   NULL    S     NULL
17   2013-07-08 16:55:26.000    E           1        38.00  3.80    17.56   667.28  4.00    P     NULL
18   2013-07-08 22:10:03.000    E           0        0.00   3.90    17.63   0.00    0.00    GT     -         
19   2013-07-08 23:03:08.000    E           2        2.00   3.50    17.50   35.00   4.00    P      -         
20   2013-07-08 23:03:22.000    E           13       3.90   3.80    17.56   68.48   4.00    P      -         

我想要一个查询来获得结果

Date, 
Session, 
Total Members for session, 
Total Litres for Session, 
Total Amount For the Session,  
Fat(Where Col1='GT') as GTFat, 
Price(Where Col1='GT') as GTPrice, 
NetAmount as GTPrice * (TotalLitres for Session), 
Profit or Loss(NetAmount-Session Amount)

请帮助我如何获得结果。

提前致谢

我尝试使用此代码但无法获得所需的结果,因为日期比较存在问题

DECLARE @t TABLE (SlNo INT IDENTITY (1, 1) NOT NULL, Date DATETIME, Session VARCHAR(30), TotalMembers INT, TotalLitres DECIMAL(8, 2), Amount DECIMAL(8, 2), 
GTFat DECIMAL(8, 2), GTPrice DECIMAL(8, 2), GTAmount DECIMAL(8, 2), PnL DECIMAL(8, 2)); 
INSERT INTO @t (Date, Session, TotalMembers, TotalLitres, Amount)        
SELECT  Cast(Date as date), Session, Count(MemberCode), Sum(Litres), Sum(Amount)  FROM   myTable Where Col1 = 'P' and Date between '2013-07-01'  and '2013-07-09' GROUP BY Cast(Date as Date), Session Order By Cast(Date as date)

declare @maxcount int,@loop int
    declare @GTAmt money,@PL money
    set @loop =1
    select @maxcount= MAX(SlNo ) from @t
while(@loop <= @maxcount)
    begin
Update @t Set GTFat = (Select Fat From myTable Where Date=Date and Session=Session and Col1='GT'),GTPrice=(Select Price From myTable Where Date=Date and Session=Session and Col1='GT')
set @loop = @loop + 1
end 
SELECT * FROM @t order by Cast(Date as date)
4

2 回答 2

0

感谢您的回答。

我通过编写存储过程获得了结果。

创建了一个临时表并收集了所有需要的数据并得到了结果。

而不是存储过程,我可以直接使用临时表......据我所知,这是第二个选项。

再次感谢

于 2014-02-27T11:59:38.080 回答
0

我相信您需要这样的东西,但是净额的真正含义是什么?你要计算吗?日期、会话、会话的成员总数、会话的总升数、会话的总金额、
Fat(Col1='GT') 作为 GTFat、价格(Col1='GT') 作为 GTPrice、NetAmount 作为 GTPrice * (TotalLitres for Session), 盈亏(NetAmount-Session Amount)

选择

 Date, 
Session, 
COUNT(Session) AS TotalnumberForSession,
SUM(amount) AS TotalSumAmount,
CASE 
    WHEN Col1 = 'GT' THEN Fat
    ELSE NULL
END AS GTPrice,
CASE 
    WHEN Col1 = 'GT' THEN Price
    ELSE NULL
END AS GTFAT,
amount*SUM(litres) OVER (PARTITION BY session)
于 2013-07-09T09:37:36.657 回答