0

我正在尝试编写一个查询,将名称添加到我的表的每一行。看起来应该很简单,但我无法弄清楚,因为我不是 SQL 专家。

这是我希望我的表看起来的样子:

         New    Cancels Net
Daily     0         1   -1
Weekly    0     1   -1
Monthly   25    34  -9
Quarterly 25    34  -9
Annually  535   552 -17
Total     3418  1398    2020

这是我现在的桌子:

New     Cancels Net
0           1   -1
0           1   -1
25          34  -9
25          34  -9
535         552 -17
3418    1398    2020

这是它背后的查询(我使用的是 SQL Server Management Studio):

SELECT [New Orders]
      ,[Cancels]
      ,[Net]
FROM [DailyFigures]
WHERE [UID]  IN (
SELECT TOP 1 [UID]
FROM [DailyFigures] 
ORDER BY [UID] DESC)
UNION ALL
SELECT [Orders]
      ,[Cancels]
      ,[Net]
FROM [WeeklyFigures]
WHERE [UID]  IN (
SELECT TOP 1 [UID]
FROM [WeeklyFigures] 
ORDER BY [UID] DESC)
UNION ALL
SELECT [Orders]
      ,[Cancels]
      ,[Net]
FROM [MonthlyFigures]
WHERE [UID]  IN (
SELECT TOP 1 [UID]
FROM [MonthlyFigures] 
ORDER BY [UID] DESC) 
UNION ALL
SELECT [Orders]
      ,[Cancels]
      ,[Net]
FROM [QuarterlyFigures]
WHERE [UID]  IN (
SELECT TOP 1 [UID]
FROM [QuarterlyFigures] 
ORDER BY [UID] DESC) 
UNION ALL
SELECT [Orders]
      ,[Cancels]
      ,[Net]
FROM [AnnuallyFigures]
WHERE [UID]  IN (
SELECT TOP 1 [UID]
FROM [AnnuallyFigures] 
ORDER BY [UID] DESC) 
UNION ALL
SELECT SUM([Orders]) AS Orders, SUM([Cancels]) AS Cancels, SUM([Net]) AS Net FROM [AnnuallyFigures]

我正在考虑添加一个带有行数的列,并以某种方式将行数从数字更改为名称,但我不知道该怎么做。任何帮助,将不胜感激。谢谢。

4

1 回答 1

2

只需为每个单独的选择添加一个“文本字符串”,如下所示:

SELECT 'DAILY' as ' ', [New Orders],[Cancels],[Net]
FROM [DailyFigures]
WHERE [UID]  IN 
  (SELECT TOP 1 [UID] FROM [DailyFigures] ORDER BY [UID] DESC) 

UNION ALL

SELECT 'WEEKLY' as ' ', [Orders],[Cancels],[Net]
FROM [WeeklyFigures]
WHERE [UID]  IN 
  (SELECT TOP 1 [UID] FROM [WeeklyFigures] ORDER BY [UID] DESC)

UNION ALL

SELECT 'MONTHLY' as ' ', [Orders],[Cancels],[Net]
FROM [MonthlyFigures]
WHERE [UID]  IN 
  (SELECT TOP 1 [UID] FROM [MonthlyFigures] ORDER BY [UID] DESC) 

UNION ALL

SELECT 'QUARTERLY' as ' ', [Orders],[Cancels],[Net]
FROM [QuarterlyFigures]
WHERE [UID]  IN 
  (SELECT TOP 1 [UID] FROM [QuarterlyFigures] ORDER BY [UID] DESC) 

UNION ALL

SELECT 'ANNUALLY' as ' ', [Orders],[Cancels],[Net]
FROM [AnnuallyFigures]
WHERE [UID]  IN 
  (SELECT TOP 1 [UID] FROM [AnnuallyFigures] ORDER BY [UID] DESC) 

UNION ALL

SELECT 'TOTAL' as ' ', 
    SUM([Orders]) AS Orders, 
    SUM([Cancels]) AS Cancels, 
    SUM([Net]) AS Net 
FROM [AnnuallyFigures]
于 2013-10-24T18:04:43.813 回答