0

表格1

ID    |      DATE       |   
 a    |   10-07-2012    |     
 b    |   10-07-2012    |     
 c    |   10-07-2012    | 

表2

ID    |    OrdersID  |
 a    |     001      |
 b    |     002      |
 c    |     003      |

表3

ItemID    |   OrdersID    |  Items |
    1     |     001       |   5    |  
    2     |     002       |   3    |  
    7     |     003       |   2    | 
    3     |     003       |   7    | 
    4     |     001       |   8    |
    2     |     003       |   7    |
    5     |     003       |   6    |   
    6     |     003       |   1    |

表4

 ItemID   | ItemName   |  
    1     |  ABC       |
    2     |  EFG       |
    3     |  HIJ       |
    4     |  KLM       |
    5     |  NOP       |
    6     |  QRS       |
    7     |  TUV       |

我想从TABLE1t 中选择 IDDate = 10-07-2012

Table2使用 ID 时,我想选择OrdersID's

OrdersID's 我想将ItemID存在的项目数加在一起,例如IteamID2 总共有 10 个项目

FromTABLE3我想知道前 5 个 Item 和 Items in Order 的数量,并获取ItemIDfrom的名称TABLLE4 ItemName

预期结果 5 个结果

ItemID  |  ItemName  |  Quantity  | 
   2    |  EFG       |     10     | 
   3    |  HIJ       |      7     | 
      .....
  .....
      .....
      .....

开始时使用的 SQL...

 SELECT SUM (t3.Items) , t4.ItemName
  FROM Table3 t3
  JOIN Table2 t2 ON t3.OrdersID = t2.OrdersID
  JOIN Table1 t1 ON t2.ID = t1.ID
  WHERE t1.[Date] = '10072012 00:00:00'
4

2 回答 2

1

您只是缺少一个GROUP BY子句和一个JOINinto Table4。您的示例结果还包括ItemID,因此我也将添加以下内容Table4

 SELECT 
   SUM(t3.Items) , 
   t4.ItemID, 
   t4.ItemName
 FROM 
   Table3 t3
   JOIN Table2 t2 ON t3.OrdersID = t2.OrdersID
   JOIN Table1 t1 ON t2.ID = t1.ID
   JOIN Table4 t4 ON t3.ItemID = t4.ItemID 
 WHERE t1.[Date] = '10072012 00:00:00'
 GROUP BY 
   t4.ItemID, 
   t4.ItemName
于 2012-08-03T02:00:07.500 回答
0

根据您想在前五名中打破平局的方式,这是一个可行的答案。

select top 5
    t3.ItemID,
    (select ItemName from TABLE4 as t4 where t4.ItemID = t3.ItemID) as ItemName,
    sum(t3.Items) as Quantity
from TABLE3 as t3
where t3.OrdersID in (
    select OrdersID
    from TABLE1 as t1 inner join TABLE2 as t2 on t2.ID = t1.ID
    where DATE = cast('20121007' as datetime)
)
group by t3.ItemID
order by Quantity desc

这是我得到的输出。请注意,第 4 项的排名高于第 3 项,后者与指定的示例输出不匹配。

ItemID | ItemName | Quantity  
   2   |    EFG   |    10  
   4   |    KLM   |     8  
   3   |    HIJ   |     7  
   5   |    NOP   |     6  
   1   |    ABC   |     5  
于 2012-08-03T02:41:04.463 回答