如何在多个UNION查询上创建动态订单?



我有一次大学练习,我必须演示如何方便地使用Union. 我正在使用一个示例TSQLV4数据库。

我写了下面的代码:
FROM
(SELECT TOP 5 
cust.companyname as [Customer], 
SUM(ord.total) AS [Total Spent],
COUNT(ord.orderid) AS [Total Orders],
'Top Spender' AS [Description]
FROM sales.Orders ord 
JOIN sales.customers cust ON cust.custid = ord.custid
GROUP BY [companyname]
ORDER BY 2 desc) base
UNION
SELECT [Customer],[Total Spent],[Total Orders],[Description]
FROM
(SELECT TOP 5 
cust.companyname as [Customer], 
SUM(ord.total) AS [Total Spent],
COUNT(ord.orderid) AS [Total Orders],
'Lowest Spender' AS [Description]
FROM sales.Orders ord 
JOIN sales.customers cust ON cust.custid = ord.custid
GROUP BY [companyname]
ORDER BY 2 ASC) base
UNION
SELECT [Customer],[Total Spent],[Total Orders],[Description]
FROM
(SELECT TOP 5 
cust.companyname as [Customer], 
SUM(ord.total) AS [Total Spent],
COUNT(ord.orderid) AS [Total Orders],
'Most Orders' AS [Description]
FROM sales.Orders ord 
JOIN sales.customers cust ON cust.custid = ord.custid
GROUP BY [companyname]
ORDER BY 3 desc) base
UNION
SELECT [Customer],[Total Spent],[Total Orders],[Description]
FROM
(SELECT TOP 5 
cust.companyname as [Customer], 
SUM(ord.total) AS [Total Spent],
COUNT(ord.orderid) AS [Total Orders],
'Least Orders' AS [Description]
FROM sales.Orders ord 
JOIN sales.customers cust ON cust.custid = ord.custid
GROUP BY [companyname]
ORDER BY 3 asc) base
order by 4,2

它返回:

tbody> <<tr>客户UISOJ客户GCJSG客户FVXPQ客户EYHKM客户VMLOG客户UISOJ客户IAIJK客户GCJSG客户MDLWA客户CYZTN客户FRXZL客户THHDP客户LCOUJ客户IRRVL客户NYUHS客户FRXZL客户THHDP客户LCOUJ客户IRRVL
客户总消费额总订单描述
客户VMLOG100.80001最小订单
357.00002最小订单
649.00003最小订单
1488.70002最小订单
1571.20003最小订单
100.80001最低支出
357.00002最低支出
522.50003最低支出
649.00003最低支出
836.70005最低支出
32555.550019大多数订单
57317.390019大多数订单
113236.680030大多数订单
115673.390031日大多数订单
117483.390028大多数订单
52245.900018开支大户
57317.390019开支大户
113236.680030开支大户
115673.390031日开支大户
117483.390028开支大户

将您的所有查询放在cte中并选择cto中的字段,然后通过

编写您的订单例句:


WITH q
AS
(
SELECT p.ProductID,p.Name,p.ModifiedDate
FROM Production.Product p
UNION 
SELECT ProductCategoryID,Name,ModifiedDate
FROM Production.ProductCategory
)
SELECT *
FROM q
ORDER BY q.Name,q.ModifiedDate

您可以在每个子查询中添加ROW_NUMBER,并使用它来排序最终结果:

SELECT s.Client , s.InvoiceAmount,s.Description,s.RN
FROM    (
SELECT TOP 5 f.Client , f.InvoiceAmount,'Small clients' as Description,ROW_NUMBER() OVER (ORDER BY f.InvoiceAmount) RN
FROM dbo.FactSales f
ORDER BY f.InvoiceAmount 
) s
UNION ALL
SELECT l.Client , l.InvoiceAmount,Description,l.RN
FROM    (
SELECT TOP 5 f.Client , f.InvoiceAmount,'Large clients' as Description,ROW_NUMBER() OVER (ORDER BY f.InvoiceAmount DESC) RN
FROM dbo.FactSales f
ORDER BY f.InvoiceAmount DESC
) l
ORDER BY Description,RN;

最新更新