1

我有以下查询:

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)

结果:

在此处输入图像描述

此查询用于按日期计算 Buy_Qty,Sell_Qty 的总和。[参考此任务:无法在查询结果中获取单个日期

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

我应该在此查询中进行哪些更改。

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

请指导我。

4

2 回答 2

1

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

于 2013-04-24T07:33:31.130 回答
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)

否则,您可以使用自我加入在您的键列上仅获取 sauda 日期加入主要结果

于 2013-04-24T08:20:46.763 回答