坚持这个查询

Stuck with this query

我的数据库是这样的

每日数据

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 服务器 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,3 月 20 日和 21 日有 23 条记录

根据 运行 这个查询,它 returns 远远超过 23。我预计只有 23 条记录。

其实不需要用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 

您可以将 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