0

これは私のテーブルで、この結果を得ることができます。各ユーザーはポイントを持っています。当月、当年に獲得したユーザー ポイントの数を表示する必要があります。

ありがとう。

--------------------------------
| userId | points | date       |
--------------------------------
| 1      | 5      | 8/25/2013  |
| 1      | 3      | 8/16/2013  |
| 1      | 2      | 8/01/2013  |
| 1      | 2      | 9/25/2013  |
| 1      | 5      | 8/25/2013  |
| 1      | 3      | 2/16/2012  |
| 2      | NULL   | NULL       |
| 2      | NULL   | NULL       |
--------------------------------

結果は次のようになります。

---------------------------------------------------
| userId | CurrentMonthpoints | CurrentYearPoints |
---------------------------------------------------
| 1      | 15                 | 17                |
| 2      | NULL               | NULL              |
---------------------------------------------------

私の要求 :

SELECT  userId, 
        (SELECT   sum(points)
            from tbl_points
            WHERE  PointsDate between '8/1/2013' and '8/31/2013') AS CurrentMonthPoints,
        (SELECT distinct SUM(points)
             from tbl_points
             WHERE PointsDate between '1/1/2014' and '12/31/2014' ) AS CurrentYearPoints
 from tbl_user_performance_points

しかし、私のクエリは次のように間違って表示されます:

---------------------------------------------------
| userId | CurrentMonthpoints | CurrentYearPoints |
---------------------------------------------------
| 1      | 15                 | 17                |
| 2      | 15                 | 17                |
---------------------------------------------------

事前の感謝

4

3 に答える 3

0
  with month_cte(userid,Current_Month) as
  (select userid,sum(Points)Current_Month from tbl_points
  where datepart(mm,PointsDate)=datepart(mm,getdate()) and datepart(YY,PointsDate)=datepart(yy,getdate()) group by userid)

   , year_cte(userid,Current_year) as
  (select userid,sum(Points)Current_Year from tbl_points
  where datepart(YY,PointsDate)=datepart(yy,getdate()) group by userid)

  select Distinct t.Userid, Current_Month, Current_Year From tbl_points T 
  left join month_cte mc on T.userid=mc.userid
  left join year_cte yc on t.userid=yc.userid
于 2013-08-29T13:57:24.747 に答える
0

クエリを修正したいだけの場合は、これに置き換えてください...

SELECT  userId, 
        (SELECT   sum(points)
            from tbl_points
            WHERE  PointsDate between '8/1/2013' and '8/31/2013' and userId= X.UserId) AS CurrentMonthPoints,
        (SELECT distinct SUM(points)
             from tbl_points
             WHERE PointsDate between '1/1/2014' and '12/31/2014' and userId = X.UserId) AS CurrentYearPoints
 from tbl_user_performance_points X
于 2013-08-29T14:07:59.573 に答える