我们有一个DB,它有几个模式,每个模式都有一个Fact表。我需要准备一个结构集,其中包含来自Fact的模式名称max(MTH_DT)以及来自每个Fact表的不同MTH_DT计数。
SCHEMA_NAME MAX(MTH_DT) DISTINCT_COUNT(MTH_DT)
SCHM_1 11/30/2015 24
SCHM_2 10/31/2015 24
SCHM_3 11/30/2015 36
SCHM_4 10/31/2015 24
SCHM_5 11/30/2015 24
如何以这种方式获取结果集?
答案 0 :(得分:0)
这就是
当您确定查询并运行查询时,只需取消注释EXECUTE语句:
<?php
//require('includes/html_table.class.php');
require_once "php/mysql.php";
require('includes/fx.php');
$debug=FALSE;
//////////////////
// DEBUG TOGGLE //
$debug = TRUE;//
//////////////////
//////////////////
// RESULT PRINT TOGGLE //
$resultOutput = TRUE;//
//////////////////
//variables
$starttime = microtime(true); //stopwatch
//all important tea off date is set below
function makeReport(){
$youngest='2015-9-21 23:59:59';
//$youngest = $startDate;
$youngest = strtotime($youngest);
$oldest=$youngest-2505600; //to figure out what plans the customer is using in the past 30 days
$arrayCompPlans = array();
$seqint=0; //for navigating arrays
$regBusHours=TRUE;
//if we want to start only looking at m-f use this code
//will be put in a function for production
$count=0; //total weekdays polled
for($x=0; $x <= 29; $x++)
{
if($regBusHours){
$day1 = strtotime("-$x day",$youngest);
$day2 = strtotime('-1 day',$day1);
if (!isweekend($day1))
{
$count=1+$count;
}
}
else $count=30;
}
echo $count;
$SQL = "SELECT *
,(PlanMinUsage/$count) AS AvgDailyUsage
,(PlanMinLimit-PlanMinUsage) AS RemainingMins
FROM (
SELECT b.company Company
, a.subid CompanyID
, c.description Plan
, a.planid PlanID
, c.monthlymins PlanMinLimit
, count(a.planid) PlanCalls
, sum(a.minsused) PlanMinUsage
FROM transactions a
INNER JOIN subscribers b
ON a.subid=b.subid
INNER JOIN plans c
ON a.planid=c.id
WHERE (a.timestamp>=1440388799 AND a.timestamp<=1442894399)
AND planid!='0'
GROUP BY a.subid,a.planid) as subQ";
debugOutStr($SQL,$debug);
$theRES = mysql_query($SQL, $db);
$seqint=0;
while($row=mysql_fetch_assoc($theRES))
{
$arrayCompPlans[]=$row;
}
print_r($arrayCompPlans);
return $arrayCompPlans;
}
$array = makeReport();
print_r($array);
$endtime = microtime(true);
$tottime=number_format(($endtime-$starttime),2,'.',',');
if($resultOutput){
debugOutStr(("<br>Total Run Time: ".$tottime." seconds<br>"),$resultOutput);
debugOutArray($array, $resultOutput);
}
答案 1 :(得分:0)
这是一种比使用INFORMATION_SCHEMA.TABLES更安全的构建动态sql的方法。我离开了小组,因为它是一个常数,所以你实际上并不需要一个小组。
declare @SQL nvarchar(MAX) = ''
select @SQL = @SQL + 'select ''' + name + ''' as SchemaName, MAX(MTH_DT) as MaxMTH_DT, COUNT(distinct MTH_DT) as DISTINCT_COUNT_MTH_DT from ' + name + '.Fact union all '
from sys.schemas
where SCHEMA_ID > 4
and SCHEMA_ID < 16384
Select @SQL = LEFT(@SQL, LEN(@SQL) - 9) + ' order by SchemaName'
select @SQL