由于之间的约会功能而导致的日期问题

时间:2013-04-24 06:43:47

标签: sql database sql-server-2005 join

我有以下查询:

SELECT   
  datediff(d, 0, sauda_date),
  Scrip_Code,
  SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty   ELSE 0 END) AS BuyQty, 
  SUM(CASE WHEN Buy_sell = 1 THEN Market_Rate ELSE 0 END) AS BuyRate, 
  SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty * Market_Rate ELSE 0 END) AS BuyAmount,
  SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty ELSE 0 END) AS SellQty, 
  SUM(CASE WHEN Buy_sell = 2 THEN Market_Rate ELSE 0 END) AS SellRate,
  (CASE WHEN SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty ELSE 0 END) >
             SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty ELSE 0 END) THEN 'BF' 
      ELSE 'BT' END ) as TradeType, 
  SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty * Market_Rate ELSE 0 END) AS SellAmount, 
  SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty ELSE 0 END) - 
  SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty ELSE 0 END) as NETQTY,
  SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty * Market_Rate ELSE 0 END) - 
  SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty * Market_Rate ELSE 0 END)as NetAmt,
  SUM(CASE WHEN Buy_sell = 2 THEN Trade_Qty * Market_Rate ELSE 0 END) - 
  SUM(CASE WHEN Buy_sell = 1 THEN Trade_Qty * Market_Rate ELSE 0 END) as PNLAmt 
FROM tradeFile 
where Inst_Type = 'FUTIDX' 
   OR Inst_Type='FUTSTK' 
  and Sauda_Date = convert(datetime,'1 Mar 2013') 
group by Scrip_Code, ExpiryDate, datediff(d,0,sauda_date)

结果:

enter image description here

此查询用于获取Buy_Qty,Sell_Qty日期之和。[参考此任务:not able to get individual date in query result

但是我们可以看到datediff(d,0,sauda_date)列(即第一列)给我一些结果,但我想在此结果中添加sauda_date作为日期。

我应该在此查询中做出哪些更改。

我通过在查询中直接添加sauda_date来尝试它,但它给了我错误。

请指导我。

2 个答案:

答案 0 :(得分:1)

如果在查询中使用GROUP BY,那么(在T-SQL的情况下)在查询的字段中,您只能使用GROUP BY中的字段或聚合函数({{1} },SUM,....)。所以你不能只添加COUNT。您应该使用聚合函数添加它。例如sauda_date。或者您可以将其添加到GROUP BY部分。

答案 1 :(得分:1)

不确定您的结果要求..

简单地在选择列表中添加sauda_date如果你在列表中包含它就不会出错,我已经尝试了belwo及其工作。

Select datediff(d,0,f.Date), 
       sum(f.price), 
      f.OrderID,
       f.Date
from test f
group by f.Date,OrderID,datediff(d,0,f.Date)

否则 你可以使用自我加入来获得加入主要结果的沙特日期