SQL UNION返回多于列

时间:2014-01-03 14:53:11

标签: sql sql-server

我有以下sql语句。将结果全部放在一列中。我想要的是让仪表板标题返回一次,然后从每个图表中的一行归属于另一列的仪表板。

SELECT 
    DashBoards.Title AS [Dash Board] 
FROM DashBoards 
GROUP BY DashBoards.Title 

UNION ALL

SELECT  
    Charts.Title AS Chart
FROM Charts 
INNER JOIN DashBoardCharts 
    ON Charts.ID = DashBoardCharts.ChartID 
INNER JOIN DashBoards 
    ON DashBoardCharts.DashBoardID = DashBoards.DashBoardID

此查询涉及三个表:

CREATE TABLE Dashboards (
    DashboardID INTEGER NOT NULL PRIMARY KEY,
    Title CHAR(50) NOT NULL,
    ISDEFAULT BIT NOT NULL,
    CompanyID INTEGER NULL
);    
INSERT INTO Dashboards
VALUES (1,'Main DashBoard', 1, NULL);

CREATE TABLE Charts (   
    ID INTEGER NOT NULL PRIMARY KEY,
    Title CHAR(50) NOT NULL,
    SPName CHAR(50) NOT NULL,
    XField CHAR(50) NOT NULL,
    YField CHAR(50) NOT NULL
);    
INSERT INTO Charts
VALUES (1,'Alerting and Monitoring', 'spGetData', 'SumType', 'SumAmount');

CREATE TABLE DashboardCharts (
    DashBoardID INTEGER NOT NULL FOREIGN KEY REFERENCES Dashboards (DashboardID),
    ChartID INTEGER NOT NULL FOREIGN KEY REFERENCES Charts (ID)
);
INSERT INTO DashboardCharts
VALUES (1, 1); 

我正在寻找的结果是这样的。

划线板图 “主要仪表板”,“销售分析”              '警报和监控' '另一个仪表板','成本管理'              '结算管理'

即。仅返回仪表板标题一次以及属于该仪表板的所有图表。

1 个答案:

答案 0 :(得分:0)

SELECT d.Title AS Dashboard, c.Title AS Chart
FROM  Dashboards AS d
      INNER JOIN DashboardCharts AS dc
        ON d.DashboardID = dc.DashboardID
      INNER JOIN Charts AS c
        ON dc.ChartID = c.ChartID

我根据提供的信息对您的表结构和数据做了一些假设。请参阅SQL Fiddle

对于将来的SQL问题,拥有表结构和数据会很有帮助。即使像表格和数据的CSV表示这样简单的事情也会大大提高您将收到的答案的质量,例如:

仪表板表

DashboardID,Title
1,'Main Dashboard'
2,'Alerting and Monitoring'