SQL联合查询在列而不是行中

时间:2018-10-02 04:18:30

标签: sql

我写了一个查询来记录来自多个表中列的总数,但是我只能将数据放入行中,如何将它们放入列中?

Select Sum(Price) AS [Totals]
From Sold

Union

  SELECT SUM(Total) as Down
    FROM
    (
     SELECT Cost as Total 
     FROM Sold
     UNION ALL
     SELECT Total as Total
     FROM Extras
     ) AS AllRowsFromT1andT2

UNION Select Sum(Valued) AS [Value]
From Sold;

感谢您的帮助:)

2 个答案:

答案 0 :(得分:1)

我相信您可以像这样简化它:

SELECT
    SUM(Price)  AS [Totals]
  , SUM(Valued) AS [Value]
  , SUM(Cost) + (SELECT SUM(Total) FROM Extras) AS [Down]
FROM Sold

您还可以为列引用添加前缀,这虽然不是绝对必要的,但会使逻辑更加明显。

SELECT
    SUM(Sold.Price)  AS [Totals]
  , SUM(Sold.Valued) AS [Value]
  , SUM(Sold.Cost) + (SELECT SUM(Extras.Total) FROM Extras) AS [Down]
FROM Sold

答案 1 :(得分:0)

SELECT
(
Select Sum(Price) AS [Totals]
From Sold
) as Totals,
(
  SELECT SUM(Total) as Down
    FROM
    (
     SELECT Cost as Total 
     FROM Sold
     UNION ALL
     SELECT Total as Total
     FROM Extras
     ) AS AllRowsFromT1andT2
) as AllRowsFromT1andT2,
(
Select Sum(Valued) AS [Value]
From Sold
) as VALUE

SQL Server可以工作,但是根据您的数据库,您可能需要强制语法。例如,在Oracle中,您需要SELECT <.. all .. >> FROM DUAL不确定MySQL或其他。