如何在函数中使用新声明的列?

时间:2017-10-05 07:04:33

标签: sql-server

我只需要获得Cnt< 6值的输出...我可以在不将它们插入新表的情况下获取它们。

SQL查询

(SELECT t3.State_Name,
          t2.Customer_Name,
          sum(t1.Qty) AS qty,(CASE
                                  WHEN (row_number()OVER (PARTITION BY t3.state_name
                                                          ORDER BY t3.state_name DESC)<6)
                              END)'Cnt'
   FROM t1
   JOIN T2 ON (t1.customer_code=t2.customer_code)
   JOIN t3 ON (t3.Area_code=t1.Area_code)
   WHERE Cnt<6
   GROUP BY State_Name,
            Customer_Name)

1 个答案:

答案 0 :(得分:2)

这里有很多示例和答案,描述了如何使用row_number()检索组中的前n行。

使用...WHERE Cnt < 6了解您要实现的目标会有所帮助。

如果您正在尝试检索每个国家/地区的前六个条目,那么您希望将查询置于子选择中,因为无法在WHERE中访问row_number()结果子句int同一个查询;做这样的事......

SELECT t.State_Name,
       t.Customer_Name,
       t.qty
FROM
(
    SELECT  t3.State_Name,
            t2.Customer_Name,
            sum(t1.Qty) AS qty,
            row_number() OVER (PARTITION BY t3.state_name ORDER BY t3.state_name DESC) AS Cnt
    FROM t1 
    INNER JOIN T2 ON t1.customer_code = t2.customer_code
    INNER JOIN t3 ON t3.Area_code = t1.Area_code
    GROUP BY State_Name,Customer_Name 
) t 
WHERE Cnt < 6

但是,这不会为您提供数量最多的六个州,也不会为您提供每个州中数量最多的六个客户。在任何一种情况下,通过与分区列相同的列进行排序将为您提供非确定性结果;您需要更改ORDER BY功能的row_number()才能使用sum(qty)

对于后者,只需更改ORDER BY ...

SELECT t.State_Name,
       t.Customer_Name,
       t.qty
FROM
(
    SELECT  t3.State_Name,
            t2.Customer_Name,
            sum(t1.Qty) AS qty,
            row_number() OVER (PARTITION BY t3.state_name ORDER BY sum(t1.Qty) DESC) AS Cnt
    FROM t1 
    INNER JOIN T2 ON t1.customer_code = t2.customer_code
    INNER JOIN t3 ON t3.Area_code = t1.Area_code
    GROUP BY State_Name,Customer_Name 
) t 
WHERE Cnt < 6

对于前者,您还需要删除PARTITION BY ...

SELECT t.State_Name,
       t.Customer_Name,
       t.qty
FROM
(
    SELECT  t3.State_Name,
            t2.Customer_Name,
            sum(t1.Qty) AS qty,
            row_number() OVER (ORDER BY sum(t1.Qty) DESC) AS Cnt
    FROM t1 
    INNER JOIN T2 ON t1.customer_code = t2.customer_code
    INNER JOIN t3 ON t3.Area_code = t1.Area_code
    GROUP BY State_Name,Customer_Name 
) t 
WHERE Cnt < 6