请帮助改进这个简单但丑陋的查询

时间:2015-05-18 09:06:36

标签: sql-server

我已经完成了查询,但看起来很难看。主要担心的是,我担心性能会很慢。

这是我的表:

ID      ProductCode         Qty        PYear      PMonth
1            A1              4          2015        2
2            A2              5          2015        2  
3            A3              2          2014       12
4            A3             16          2015        4

我想获得每种产品的最新销售日期类别,下面是我想要的结果:

ProductCode         Qty         Year      Month
     A1              4          2015        2
     A2              5          2015        2  
     A3             16          2015        4

看起来很简单,但我的查询很复杂,我打赌必须有一个简单的解决方案,下面是我正在使用的查询,我将年份和月份加入到1列中:

SELECT A.ProductCode, B.Qty, PDate 
FROM (
    SELECT MAX(ID) AS purchaseID, 
    ProductCode, 
    MAX(CAST(PYear AS VARCHAR(4)) + '-' + CAST(PMonthAS VARCHAR(2)) + '-1') AS PDate
    FROM Table1
    GROUP BY ProductCode
) AS B
LEFT JOIN Table1 AS B ON A.ID= B.ID

2 个答案:

答案 0 :(得分:2)

使用窗口函数应该可以解决问题 - 这会根据降序日期为每条记录添加一行,并按产品代码分组

SELECT 
purchaseID
,ProductCode
,Qty
,Pdate
FROM
( 
SELECT 
purchaseID 
,Qty
,ProductCode 
,CAST(PYear AS VARCHAR(4)) + '-' + CAST(PMonthAS VARCHAR(2)) + '-1') AS PDate
,ROW_NUMBER() OVER (PARTITION BY ProductCode ORDER BY CAST(PYear AS VARCHAR(4)) + '-' + CAST(PMonthAS VARCHAR(2)) + '-1') DESC) AS ROWNO
FROM Table1 
)
WHERE ROWNO = 1

答案 1 :(得分:2)

您可以将ROW_NUMBER与CTE一起使用吗?在这种情况下,您实际上不需要使用JOIN

;WITH CTE AS (
  SELECT *, ROW_NUMBER() OVER(PARTITION BY PRODUCTCODE ORDER BY PYEAR DESC, PMONTH DESC) AS RN
  FROM TABLE1)
 SELECT PRODUCTCODE, QTY, PYEAR, PMONTH
 FROM CTE
 WHERE RN = 1

这是一个SQL小提琴:http://sqlfiddle.com/#!6/90fe1/1