SQL Unique Values Numbering Sequence for Pivot

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

For reporting purcposes, I need to Pivot results of a query that is unique on each record. My current statement is:

SELECT * FROM Sales AS x WHERE (select count(*) from Sales where customer_name=x.customer_name          and order_date>=x.order_date)<=5 ORDER BY customer_name, order_date, price; 

A sample of the Query output is:

customer_name    order_date        price Company A        2009-02-01        800  Company A        2009-03-01        100 Company A        2009-04-01        200 Company A        2009-05-01        300 Company A        2009-06-01        500 Company B        2009-02-01        100 Company B        2009-02-01        800 Company B        2009-04-01        200 Company B        2009-05-01        300 Company B        2009-06-01        500 

Ultimately, the information needs to look like this:

Customer_Name     order_date1  price1    order_date2  price2    order_date3  price3    order_date4  price4    order_date5  price5    Company A         2009-02-01   800       2009-03-01   100       2009-04-01   200       2009-05-01   300       2009-06-01   500 Company B         2009-02-01   100       2009-02-01   800       2009-04-01   200       2009-05-01   300       2009-06-01   500 

I'm thinking that I need to add a column for "pivot_id" so that there is a common record for each grouping so the query result before the pivot will look like:

pivot_id  customer_name    order_date        price 1         Company A        2009-02-01        800  2         Company A        2009-03-01        100 3         Company A        2009-04-01        200 4         Company A        2009-05-01        300 5         Company A        2009-06-01        500 1         Company B        2009-02-01        100 2         Company B        2009-02-01        800 3         Company B        2009-04-01        200 4         Company B        2009-05-01        300 5         Company B        2009-06-01        500 

What SQL statment will generate an automatic record number for each purchase, but also start over with each customer_name??

Working in Access 2007 with SQL code builder. Would be great if solution is compatible with Access.

Sorry for the length. Thanks in advance.

回答1:

How about another correlated subquery? Save you Query, say as Query1 (you probably want to remove the ORDER BY clause from this intermediate Query -- only need to sort the final resultset):

SELECT Q1.customer_name, Q1.order_date, Q1.price,         (         SELECT COUNT(*) + 1           FROM MyQuery AS Q2          WHERE Q2.customer_name = Q1.customer_name                AND Q2.order_date < Q1.order_date        ) AS pivot_id   FROM MyQuery AS Q1; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!