SQL Server:查询数量

时间:2012-08-03 01:55:31

标签: sql-server

表1

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

TABLE2

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       |

我想从TABLE1 t Date = 10-07-2012

中选择ID

在带有ID的Table2中,我想选择OrdersID

对于OrdersID,我想将ItemID中存在的项目加在一起,例如IteamID 2共有10个项目

TABLE3我想了解前5项和订单中的商品数量,并从ItemID TABLLE4获取ItemName的名称。< / p>

预期结果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'

2 个答案:

答案 0 :(得分:1)

您只是错过GROUP BY条款,JOIN错过了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

答案 1 :(得分: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