我的查询如下:
SELECT CONVERT(VARCHAR(10),[start_of_week],103) AS WEEK_START, VisitorCount FROM mytable2
UNION
SELECT 'Average' AS WEEK_START,AVG(VisitorCount) from mytable2
ORDER BY WEEK_START
如果我运行顶部查询,我会将所有内容排序为WEEK_START但是当我联合查询“平均”时,排序顺序会搞砸。 任何人都可以告诉我如何才能对所有WEEK_Start进行排序并将“平均值”排在最后?
更新 完整的查询是
DECLARE @From DATE = '2015-07-01'
DECLARE @To DATE = (SELECT GETDATE())
DECLARE @dt DATE = '1905-01-02';
WITH mytable as(
SELECT
1 as visitor,
DATEDIFF(week, '', date) AS WeekNumber,
DATEADD(WEEK, DATEDIFF(WEEK, @dt, [Date]), @dt) AS [start_of_week]
FROM Showroom_perf
Where [Date] <= @To
) , mytable2 AS (
Select
[start_of_week],
COUNT(visitor) as VisitorCount
from mytable WHERE WeekNumber > '0'
GROUP BY
[start_of_week]
)
SELECT CONVERT(VARCHAR(10),[start_of_week],103) AS WEEK_START, VisitorCount, 1 as tag FROM mytable2
UNION
SELECT 'Average' , AVG(VisitorCount), 2 as tag from mytable2
答案 0 :(得分:4)
更好的方法
使用ROLLUP
SELECT CASE
WHEN Grouping(CONVERT(VARCHAR(10), start_of_week, 103)) = 1 THEN 'Average'
ELSE CONVERT(VARCHAR(10), start_of_week, 103)
END AS WEEK_START,
Avg(VisitorCount)
FROM Yourtable
GROUP BY CONVERT(VARCHAR(10), start_of_week, 103) WITH rollup
Order by start_of_week
答案 1 :(得分:2)
只需为订单添加一个新列,并为union的每个部分赋予不同的值。由于您无法在输出中添加其他列,因此可以使用CTE稍后将其删除:
WITH temp as (
SELECT CONVERT(VARCHAR(10),[start_of_week],103) AS WEEK_START, VisitorCount, 1 as Ord
FROM mytable2
UNION
SELECT 'Average' AS WEEK_START,AVG(VisitorCount), 2 as Ord
from mytable2
)
SELECT WEEK_START, VisitorCount
FROM temp
ORDER BY Ord, WEEK_START
SQL Fiddle demo(简化示例)
答案 2 :(得分:1)
在SELECT
子句中创建一个虚拟列以指定Order By。
下面我为此目的使用了一个名为tag
的列。
SELECT CONVERT(VARCHAR(10),[start_of_week],103) AS WEEK_START, VisitorCount FROM mytable2, 1 as tag
UNION
SELECT 'Average' AS WEEK_START,AVG(VisitorCount),2 from mytable2
ORDER BY tag,WEEK_START
因此,第一个订单将在标记列上工作,将顶部查询结果推送到顶部,然后在UNION
运算符下面的查询上进行排序。