Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 使表ID显示为列,并跨所有表进行选择_Sql_Sql Server 2008_Union - Fatal编程技术网

Sql 使表ID显示为列,并跨所有表进行选择

Sql 使表ID显示为列,并跨所有表进行选择,sql,sql-server-2008,union,Sql,Sql Server 2008,Union,我的上级要求我写一个查询,搜索数据库中的每个表(每一条道路的代表及其交通总量),并按小时计算摩托车的总量。到目前为止,我在一张桌子上测试时得到了以下信息: WITH totalCount AS ( SELECT DATEDIFF(dd,0,event_time) AS DaySerial, DATEPART(dd,event_time) AS theDay, DATEDIFF(mm,0,event_time) AS MonthSerial,

我的上级要求我写一个查询,搜索数据库中的每个表(每一条道路的代表及其交通总量),并按小时计算摩托车的总量。到目前为止,我在一张桌子上测试时得到了以下信息:

    WITH
totalCount AS
(
 SELECT DATEDIFF(dd,0,event_time) AS DaySerial,
        DATEPART(dd,event_time) AS theDay,
        DATEDIFF(mm,0,event_time) AS MonthSerial,
        DATEPART(mm,event_time) AS MonthofYear,
        DATEDIFF(hh,0,event_time) AS HourSerial,
        DATEPART(hh,event_time) AS Hour,
        COUNT(*) AS HourlyCount,
        DATEDIFF(yy,0,event_time) AS YearSerial,
        DATEPART(yy,event_time) AS theYear    
   FROM [RUD].dbo.[10011E]
   WHERE length <='1.7'
  GROUP BY DATEDIFF(hh,0,event_time), 
           DATEPART(hh,event_time),
           DATEDIFF(dd,0,event_time), 
           DATEPART(dd,event_time),
           DATEDIFF(mm,0,event_time), 
           DATEPART(mm,event_time),
           DATEDIFF(yy,0,event_time), 
           DATEPART(yy,event_time)
)
    SELECT 
        theYear,
        MonthofYear,
        theDay,
        Hour,
        AVG(HourlyCount) AS Avg_Count                   
    FROM 
        totalCount
    GROUP BY 
        theYear,
        MonthofYear,
        theDay,
        Hour
    ORDER BY
        theYear,
        MonthofYear,
        theDay,
        Hour
与
总数计为
(
选择DATEDIFF(dd,0,事件\时间)作为DaySerial,
日期部分(dd,事件时间)作为日期,
DATEDIFF(毫米,0,事件时间)作为月份,
DATEPART(毫米,事件时间)为MonthofYear,
DATEDIFF(hh,0,事件时间)作为小时序列,
日期部分(hh,事件时间)为小时,
按小时计数(*),
DATEDIFF(yy,0,事件时间)为YearSerial,
日期部分(yy,事件时间)作为年份
FROM[RUD].dbo[10011E]

其中length一个选项是使用
UNION ALL
并为哪个源添加额外的列。在这种情况下,您必须写出每个表,但这可能是您最快的选项:

SELECT ID, 'YourTable' TableName
FROM YourTable
UNION ALL
SELECT ID, 'YourOtherTable' 
FROM YourOtherTable
....
或者,动态sql也可以产生相同的结果——您可能不必键入所有的表名,但它会对性能造成影响