0

我有一张表(消费)如下:

DocDate   ItemCode    Quantity
01.01.09  A           5
02.01.09  A           6

等等..全年

我需要如下结果:

ItemCode Jan09Total Feb09Total Mar09Total

问题是应该对月份的数量进行汇总,这些数量应该在列中并根据给定的日期标准,例如从 1 月到 3 月 9 日或 2 月到 7 月 9 日等。

如何使用递归查询来实现这一点。

谢谢拉胡尔

4

4 回答 4

2

Assuming you use a DB which supports PIVOT, you should use it. Here's example code for Oracle:

CREATE TABLE Consumption (
  DocDate  DATE,
  ItemCode VARCHAR2(10),
  Quantity NUMBER
);

INSERT INTO Consumption VALUES(to_date('2009-01-01', 'YYYY-MM-DD'), 'A', 5);
INSERT INTO Consumption VALUES(to_date('2009-02-01', 'YYYY-MM-DD'), 'A', 6);
INSERT INTO Consumption VALUES(to_date('2009-01-01', 'YYYY-MM-DD'), 'B', 5);

SELECT * FROM Consumption
PIVOT(
  sum(Quantity)
  FOR DocDate IN (
    to_date('2009-01-01', 'YYYY-MM-DD') AS Jan09Total,
    to_date('2009-02-01', 'YYYY-MM-DD') AS Feb09Total
  )
);

As noted by Robin, if your columns vary, then you will have to dynamically generate such a query with the correct columns.

于 2009-06-01T12:27:50.903 回答
1

好吧,它不是递归的,但这会让你得到你想要的:

SELECT
    DateName(month, DocDate) + ' ' + CAST(YEAR(DocDate) AS VARCHAR(10)) AS MonthYear,
    ItemCode,
    SUM(Quantity)
FROM
    Consumption
GROUP BY
    DateName(month, DocDate) + ' ' + CAST(YEAR(DocDate) AS VARCHAR(10)) AS MonthYear,
    ItemCode
ORDER BY
    1,2

我认为递归只会阻碍这个查询的性能。你确定要这样做吗?或者这只是家庭作业?

于 2009-06-01T12:12:41.137 回答
0

Here is a link to a wonderfully elegant way of implementing pivot logic on KNOWN x-axis values. Dynamic pivots are more difficult.

I didn't read this article fully, so if it isn't helpful then look up "The Rozenshtein Method"

http://www.stephenforte.net/default.aspx?date=2003-08-07

I've used this in many queries with great results.

于 2009-06-01T12:31:38.850 回答
0

您可以根据需要使用 PIVOT 将数据放入列中,但是,需要事先定义列列表。因此,您需要为您需要的列(基于您的日期范围)构建一些动态 SQL,然后运行它来生成您的 PIVOT。

于 2009-06-01T12:14:27.140 回答