Sorting query output by Month name

会有一股神秘感。 提交于 2020-06-17 09:08:47

问题


I am trying to extract values from Excel using an SQL Query, but what I've been struggling with is sorting the months in their respective order. Right now the table is being sorted A-Z, I tried playing around with DATEPART, but was not very successful as I was getting an Int16 error.

Select F1,
SUM(F2),
ROUND(SUM(REPLACE(F3, ',', '.')), 2),
ROUND(SUM(REPLACE(F4, ',', '.')), 2)
FROM [Sheet1$]
WHERE F1 IN ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December')
GROUP BY F1;

This is the query that works, but the result is:

I am also open to any suggestions that could improve my query speed as the document is quite big, about 50k rows, thanks.

For anyone wondering the final query that worked was:

Select F1,
SUM(F2),
ROUND(SUM(REPLACE(F3, ',', '.')), 2),
ROUND(SUM(REPLACE(F4, ',', '.')), 2)
FROM [Sheet1$]
WHERE F1 IN ('January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December')
GROUP BY F1
ORDER BY SWITCH(
F1='January', 1,
F1='February', 2,
F1='March', 3,
F1='April', 4,
F1='May', 5,
F1='June', 6,
F1='July', 7,
F1='August', 8,
F1='September', 9,
F1='October', 10,
F1='November', 11,
F1='December', 12
);

回答1:


Either use a CASE expression:

Select
  f1,
  SUM(f2),
  ROUND(SUM(REPLACE(f3, ',', '.')), 2),
  ROUND(SUM(REPLACE(f4, ',', '.')), 2)
FROM [Sheet1$]
WHERE F1 IN ('January', 'February', 'March', 'April', 'May', 'June',
             'July', 'August', 'September', 'October', 'November', 'December')
GROUP BY F1
ORDER BY
  CASE F1
    WHEN 'January' THEN 1
    WHEN 'February' THEN 2
    WHEN 'March' THEN 3
    WHEN 'April' THEN 4
    WHEN 'May' THEN 5
    WHEN 'June' THEN 6
    WHEN 'July' THEN 7
    WHEN 'August' THEN 8
    WHEN 'September' THEN 9
    WHEN 'October' THEN 10
    WHEN 'November' THEN 111
    WHEN 'December' THEN 12
  END;

Or create a month table on the fly:

Select
  s.f1,
  SUM(s.f2),
  ROUND(SUM(REPLACE(s.f3, ',', '.')), 2),
  ROUND(SUM(REPLACE(s.f4, ',', '.')), 2)
FROM [Sheet1$] s
JOIN VALUES
(
  ('January', 1),
  ('February', 2),
  ('March', 3),
  ('April', 4),
  ('May', 5),
  ('June', 6),
  ('July', 7),
  ('August', 8),
  ('September', 9),
  ('October', 10),
  ('November', 11),
  ('December', 12)
) months(month_name, month_number) ON s.f1 = months.month_name
GROUP BY s.f1
ORDER BY months.month_number;

Or create a real month table.




回答2:


You could do:

order by datepart(mm, f1 + ' 1 2000')


来源:https://stackoverflow.com/questions/62149401/sorting-query-output-by-month-name

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