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 に答える