选择不同的列,但根据区别包括结果中另一列的前1位

时间:2017-07-25 09:31:30

标签: sql sql-server

我有一个6列的产品表。产品属于一种类型,类型属于一类。

我选择了4列,我使用DISTINCT来检索一组结果....

SELECT DISTINCT category, type, catlong, typelong 
FROM products 
WHERE catlong = @getcatlong 
ORDER BY type

这根据我的查询字符串参数列出了产品类型及其类别名称。

示例...

 category            type              catlong            typelong
----------------------------------------------------------------------
Drink Cups       Big Drink Cups       drink-cups        big-drink-cups
Drink Cups       Med Drink Cups       drink-cups        med-drink-cups
Drink Cups       Small Drink Cups     drink-cups        small-drink-cups

在同一个表中我们生成了上面的查询,还有productname,productpicfilename的列。每种类型和类别都有几个产品图片文件名,并且都是唯一的。我需要重写查询以包含每种类型的前1个productpicfilename。

示例...

 category            type              catlong            typelong         procuctfilename
--------------------------------------------------------------------------------------------
Drink Cups       Big Drink Cups       drink-cups        big-drink-cups     redsolocups.jpg
Drink Cups       Med Drink Cups       drink-cups        med-drink-cups     bluesipcups.jpg
Drink Cups       Small Drink Cups     drink-cups        small-drink-cups   pinkdixiecups.jpg

我不确定如何处理这个问题。我尝试了多种不同类型的查询,但它们要么返回不需要的结果,要么返回错误。如果需要,我会修改此页面的标题。谢谢。

2 个答案:

答案 0 :(得分:0)

只需切换到聚合而不是DISTINCT:

SELECT category, type, catlong, typelong, MIN(procuctfilename)
FROM products 
WHERE catlong = @getcatlong 
GROUP BY category, type, catlong, typelong 
ORDER BY type

答案 1 :(得分:0)

您可以使用GROUP BY。见https://docs.microsoft.com/en-us/sql/t-sql/queries/select-group-by-transact-sql

SELECT category, type, catlong, typelong, MAX( procuctfilename ) AS procuctfilename 
FROM products 
WHERE catlong = @getcatlong 
ORDER BY category, type, catlong, typelong

另一种方法是使用Window Functions

SELECT category, type, catlong, typelong, procuctfilename
FROM
( SELECT category, type, catlong, typelong, procuctfilename,
    -- Split all rows into groups (same as GROUP BY) and calculate order within each group
    ROW_COUNT() OVER( PARTITION BY category, type, catlong, typelong ORDER BY procuctfilename ) AS TopRow
FROM products
WHERE catlong = @getcatlong ) AS TopRows
WHERE TopRow = 1 -- returns only the first row from each group
ORDER BY category, type, catlong, typelong

此查询本质上是一个"内联"上述GROUP BY查询的版本。这种方法的优点是所有列都将始终属于同一行。例如,当您想要显示与productname对应的procuctfilename时,这很有用。