SQL Hasmany查询选择1

时间:2018-12-04 15:10:24

标签: sql sql-server

我有两个要查询的表。

库存表

  • 股票代码
  • 股票名称
  • Physical_Stock

订单表

  • 订购日期
  • 数量
  • 股票代码

我拥有的所有库存记录中,实际库存大于0以及订购的最后日期。

我认为可以通过以下查询进行操作,但这会根据有多少个订单重复库存记录。

SELECT
    Stock_Code,
    Physical_Stock,
    Order_Date
FROM Stock_Table
INNER JOIN Order_Table
    ON Stock_Table.Stock_code = Order_Table.Stock_Code
WHERE Physical_Stock <> 0

4 个答案:

答案 0 :(得分:4)

大于0或<> 0是什么?

您只需要使用聚合函数max()来获取最大订单日期,因为可以为给定的股票代码下达多个订单。并且由于您使用聚合,因此非聚合列需要使用group by。

SELECT Stock_Code, Physical_Stock, max(Order_Date)
FROM Stock_Table 
INNER JOIN Order_Table 
  ON Stock_Table.Stock_code = Order_Table.Stock_Code
WHERE Physical_Stock <> 0
GROUP BY Stock_Code, Physical_Stock

答案 1 :(得分:2)

--So, what is happening, we use ROW_NUMBER() OVER and PARTITION BY
--ROW_NUMBER() Adds in the number for that particular record based on the PARTITION BY
--stock_code then orders the records by the order_date Descending
--Then selects from the subquery each record with row number = 1
--This produces the first record for each unique stock_code
--and since it is ordered by order_date descending, you get the most
--recent purchase
SELECT *
FROM
(
   SELECT st.stock_code, physical_stock, order_date, ROW_NUMBER() OVER(PARTITION BY 
   st.[stock_code] ORDER BY [order_date] DESC) AS [Row_Number]
   FROM Stock_Table AS st 
   INNER JOIN Order_Table AS ot 
   ON st.stock_code = ot.stock_code
) AS x
Where x.physical_stock <> 0 AND x.[Row_Number] = 1

答案 2 :(得分:1)

以下是交叉应用排名前1的解决方案:

SELECT Stock_Code, Physical_Stock, Order_Date
FROM 
    Stock_Table
    CROSS APPLY
    (
        SELECT TOP 1 Order_Date
        FROM Order_Table 
        WHERE Stock_Table.Stock_code = Order_Table.Stock_Code
        order by Order_Date desc
    )q
Where Physical_Stock <> 0

如果需要,您还可以从最近的订购日期开始添加更多列。

答案 3 :(得分:0)

使用GroupBy

SELECT 
  Stock_Table.Stock_Code, 
  Max(Physical_Stock) As Stock, 
  Max(Order_Date) As LastDate
FROM  
  Stock_Table INNER JOIN 
  Order_Table ON Stock_Table.Stock_code = Order_Table.Stock_Code
Where Physical_Stock > 0
Group By Stock_Table.Stock_Code