我正在尝试编写一个查询,为表格的每一行添加名称。看起来它应该很简单但我无法理解,因为我不是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]
我正在考虑添加一个包含行计数的列,并以某种方式将行数从数字更改为名称,但我不知道该怎么做。任何帮助,将不胜感激。感谢。
答案 0 :(得分: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]