我一直在尝试编写一个下面的SQL查询,并在查询下面给出结果

时间:2017-06-20 12:23:39

标签: sql

select
     TRN_ADP_Items_Tracker.request_id,
     TRN_ADP_Stationary_Request.requester_name,
     item_id,   
    case when MONTH(TRN_ADP_Items_Tracker.ITEM_QTY_TRADE_DATE)=6 then sum(item_qty_traded) else 0 end as JUNE,
    case when MONTH(TRN_ADP_Items_Tracker.ITEM_QTY_TRADE_DATE)=7 then sum(item_qty_traded) else 0 end as JULY,
    case when MONTH(TRN_ADP_Items_Tracker.ITEM_QTY_TRADE_DATE)=8 then sum(item_qty_traded) else 0 end as AUG

  from TRN_ADP_Items_Tracker
  join TRN_ADP_Stationary_Request
  on TRN_ADP_Items_Tracker.request_id  =  TRN_ADP_Stationary_Request.stationary_request_id
  group by TRN_ADP_Stationary_Request.requester_name,item_id,
      MONTH(TRN_ADP_Items_Tracker.ITEM_QTY_TRADE_DATE);
request requester item
_id      _name    _id    JUNE   JULY    AUG 
3   Prasad    150    2  0   0
3   Prasad    154    2  0   0
1   Sneha     150    15 0   0
1   Sneha     150    0  15  0
1   Sneha     150    0  0   6
1   Sneha   154 4   0   0

但是我想要结果如下: -

request_id  requester_name  item_id  JUNE  JULY  AUG 
1        Sneha      150      15     15    6

如果第3列数据相同,那么月数据应该排在第1行,如上所述。

2 个答案:

答案 0 :(得分:0)

you need to correct your GROUP_ID to have only three columns from your select

select
 TRN_ADP_Items_Tracker.request_id,
 TRN_ADP_Stationary_Request.requester_name,
 item_id

from

group by TRN_ADP_Stationary_Request.requester_name,item_id,
  MONTH(TRN_ADP_Items_Tracker.ITEM_QTY_TRADE_DATE)

答案 1 :(得分:0)

需要从选择列表中取出request_id列。

select
         --TRN_ADP_Items_Tracker.request_id,
         TRN_ADP_Stationary_Request.requester_name,
         item_id,   
        case when MONTH(TRN_ADP_Items_Tracker.ITEM_QTY_TRADE_DATE)=6 then sum(item_qty_traded) else 0 end as JUNE,
        case when MONTH(TRN_ADP_Items_Tracker.ITEM_QTY_TRADE_DATE)=7 then sum(item_qty_traded) else 0 end as JULY,
        case when MONTH(TRN_ADP_Items_Tracker.ITEM_QTY_TRADE_DATE)=8 then sum(item_qty_traded) else 0 end as AUG

      from TRN_ADP_Items_Tracker
      join TRN_ADP_Stationary_Request
      on TRN_ADP_Items_Tracker.request_id  =  TRN_ADP_Stationary_Request.stationary_request_id
      group by TRN_ADP_Stationary_Request.requester_name,item_id,
          MONTH(TRN_ADP_Items_Tracker.ITEM_QTY_TRADE_DATE);