为了报告目的,我需要透视每个记录上唯一的查询结果。我当前的声明是:
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;
查询输出的示例是:
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
最终,信息需要看起来像这样:
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
我在想我需要为“ pivot_id”添加一列,以便每个分组都有一个共同的记录,因此在数据透视之前的查询结果将如下所示:
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
哪种SQL语句将为每次购买生成一个自动记录号,而且还会从每个customer_name重新开始?
使用SQL代码生成器在Access 2007中工作。如果解决方案与Access兼容,那就太好了。
抱歉,长度不够。提前致谢。
另一个相关的子查询怎么样?将您的查询保存为Query1(您可能希望ORDER BY从此中间Query中删除该子句-只需对最终结果集进行排序):
ORDER BY
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;