SQL,获取前2行并将字段转换为列

时间:2013-07-18 16:08:31

标签: sql multiple-columns

我正在尝试完成对我来说是一个复杂的查询,我有点卡住了。 我正在返回几行,但我只想要前两行,我需要将ItemNum列转换为两列Item1&项目2 所以我有一个看起来像这样的结果集。数据源将包含1 - 每个电子邮件和类别的任意行数。

Email           Category ItemCount  Date                    ItemNum
jimbo@GMAIL.COM CASE FANS   3       2013-07-16 00:00:00.0   11-999-344
jimbo@GMAIL.COM CASE FANS   3       2013-07-16 00:00:00.0   35-103-178
jimbo@GMAIL.COM CASE FANS   3       2013-07-16 00:00:00.0   35-129-060
miyaa@YAHOO.COM CASE FANS   4       2013-07-16 00:00:00.0   35-146-003
miyaa@YAHOO.COM CASE FANS   4       2013-07-16 00:00:00.0   35-146-017
miyaa@YAHOO.COM CASE FANS   4       2013-07-16 00:00:00.0   35-146-017
miyaa@YAHOO.COM CASE FANS   4       2013-07-16 00:00:00.0   35-146-017

我希望结果看起来像这样

Email           Category    Date                    Item1         Item2
jimbo@GMAIL.COM CASE FANS   2013-07-16 00:00:00.0   11-999-344    35-103-178  
miyaa@GMAIL.COM CASE FANS   2013-07-16 00:00:00.0   11-999-344    35-103-178  

因此,为了增加挫败感,我无法使用TempTables或声明任何varibales。

任何帮助都将不胜感激。

由于

3 个答案:

答案 0 :(得分:1)

试试这个:

select a1.email, a1.itemNum, 
(select distinct a3.itemNum
    from myTable a3
    where a3.email = a1.email
    and a3.itemNum > a1.itemNum
    and not exists(
        select 'x' from myTable a4
        where a4.email = a3.email
        and a4.itemNum > a1.itemNum
        and a4.itemNum < a3.itemNum)
)
from myTable a1
where not exists
(select 'x' from myTable a2
where a2.email = a1.email
and a2.itemNum < a1.itemNum)

我认为你的字段歧视是电子邮件(几行相同)和itemNum。

您可以更改现有条件的标准。

答案 1 :(得分:0)

试试这个

;WITH Ranked AS 
(
    select  Email, Category, ItemNum, ROW_NUMBER() OVER ( PARTITION BY  Email, Category ORDER BY ItemCount, Date) AS RowNo
    from MyTable
)
, TopFirst AS 
(
    SELECT Email, Category, ItemNum, RowNo
    FROM Ranked
    WHERE RowNo = 1
)
, TopSecond AS 
(
    SELECT Email, Category, ItemNum, RowNo
    FROM Ranked
    WHERE RowNo = 2
)
SELECT TopFirst.Email, TopFirst.Category, TopFirst.ItemNum AS Item1, ISNULL(TopSecond.RowNo, '')
FROM TopFirst
LEFT OUTER JOIN TopSecond ON TopFirst.Email = TopSecond.Email AND  TopFirst.Category  =  TopSecond.Category 

答案 2 :(得分:0)

根据您使用的数据库,您可以尝试将以下内容添加到SELECT语句中(我无法对您的代码进行测试,因此这可能需要修改):

SELECT email OVER(PARTITION BY email, ItemNum ORDER BY email) as EmailPartition

这不能解决为每个项目添加列的问题,但这是一个可行的选项,用于整理您的电子邮件列表并选择DISTINCT电子邮件/ ItemNum列表。这与Joe Taras的回答相结合应该可以产生有效的查询。