坚持这个查询

时间:2017-03-22 08:39:40

标签: sql sql-server-ce

我的数据库看起来像这样

DailyData

rID int
Stock varchar
rDate date
Shares int
price float

我要做的是获取两个日期的数据。

示例数据

rID    stock    rDate        Shares    price
11     Stock1   21/03/2016   15        1.22
12     Stock2   21/03/2016   22        2.23
13     Stock3   21/03/2016   17        3.32
14     Stock4   21/03/2016   10        4.24
15     Stock1   22/03/2016   15        1.25
16     Stock2   22/03/2016   20        2.27
17     Stock3   22/03/2016   17        3.32
18     Stock1   23/03/2016   15        1.28
19     Stock2   23/03/2016   20        2.20
20     Stock3   23/03/2016   17        3.32
21     Stock4   23/03/2016   10        4.24

预期输出

Stock       Shares-21    Shares-20
Stock1      15           15
Stock2      22           20
Stock3      17           17
Stock4      10           0

我对SQL Server CE数据库的查询:

Select 
    DD1.Stock, sum(DD1.Shares) as Shares-21, sum(DD2.shares) as Shares-20
from 
    DailyData DD1, DailyData DD2
where 
    DD1.rDate = '21/03/2016' and DD2.rDate = '20/03/2016' 
    and DD1.Stock = DD2.Stock
group by 
    DD1.Stock

我得到7行数据而不是4行。

请帮助查询。

*******************************新修改************** ******* 我按照建议遵循,但似乎没有奏效。这是一个真正的sql脚本。

Select P.pName,DD.Stock, 
  sum(case DD.rDate when '03/21/2016' then DD.Shares  else 0 end) as Shares21, 
  sum(case DD.rDate when '03/20/2016' then DD.Shares else  0 end) as Shares20
from dailyData DD, Portfolios P
where DD.rDate = '03/21/2016' or DD.rDate = '03/20/2016'
  and DD.pID = P.pID
  and DD.pID=1
group by P.pName,DD.stock
order by P.pName,DD.Stock

现在对于pID = 1,20-Mar和21-Mar有23条记录

运行此查询后,它返回的方式超过23.我只期待23条记录。

2 个答案:

答案 0 :(得分:3)

实际上它不需要使用JOIN。您可以像这样使用CASE WHEN语句

SELECT stock, 
       Sum(CASE rdate 
             WHEN '21/03/2016' THEN shares 
             ELSE 0 
           END) AS Shares21, 
       Sum(CASE rdate 
             WHEN '20/03/2016' THEN shares 
             ELSE 0 
           END) AS Shares20 
FROM   dailydata 
WHERE  rdate = '21/03/2016' 
        OR rdate = '20/03/2016' 
GROUP  BY stock 

答案 1 :(得分:0)

您可以将PIVOT与DATEPART一起使用

      SELECT Stock, [21] AS [Shares-21], [20] AS [Shares-20] FROM
      (
         SELECT s.Stock, Datepart(d,s.rDate) rDate , s.Shares FROM DailyData s
      ) src
      PIVOT
      (
         MAX(Shares) for rDate in ([21], [20])
      ) pvt