我正在编写一个查询,显示每周销售两年的销售情况。所以我想比较不同年份的周数。我得到了这样的结果(week
是该年内的周数,如第一周,2010年的第二周):
week|year|price
1 |2010|5
1 |2011|10
2 |2010|7
2 |2011|13
一切都会好的,但是当我尝试在图表中显示结果时,它会计算前几周等等,并将其放在一个字段中。因此,在图表中,我看到第一周的销售额为15周,秒数为20周。 所以我接着尝试将周列与另一列结合起来,将不同年份的同一周数分开。
SELECT
min(so.id) as id,
date_part('week', so.date_order) || ' ' ||
CASE
WHEN
so.date_order >='2010-01-01' and so.date_order <= '2010-12-31'
THEN
'2010'
WHEN
so.date_order >='2010-01-01' and so.date_order <= '2011-12-31'
THEN
'2011'
END as week,
date_part('year', so.date_order) as year,
count(*) as amount,
sum(sol.price_unit) as price
FROM
sale_order as so,
sale_order_line as sol
WHERE
sol.order_id=so.id and
so.date_order >= '2010-01-01' and so.date_order <= '2011-12-31'
GROUP BY
week,
year
但是,列周被排序为char类型,我得到的结果是这样的:
week |year|sales
1 - 2010 |2010|5
1 - 2011 |2011|10
10 - 2010|2010|15
11 - 2011|2011|12
2 - 2010|2010|7
2 - 2011|2011|13
如果我尝试ORDER BY to_number(week, text(99999999))
,我会收到week
列不存在的错误。我想因为那是临时专栏?
所以我的问题是,如何按临时周列进行正确排序,还是有更好的方法对其进行排序?:)
答案 0 :(得分:1)
我可能会像这样重写你的查询:
SELECT
MIN(id) AS id,
week || ' ' || year AS week,
year,
COUNT(*) AS amount,
SUM(price_unit) AS price
FROM (
SELECT
so.id,
DATE_PART('week', so.date_order) AS week,
DATE_PART('year', so.date_order) AS year,
sol.price_unit
FROM sale_order AS so
INNER JOIN sale_order_line AS sol ON sol.order_id = so.id
WHERE so.date_order BETWEEN '2010-01-01' AND '2011-12-31'
) AS x
GROUP BY
year,
week
ORDER BY
week::int,
year