如果标题不清楚,我会嗤之以鼻。
这是我的问题。
我创建了一个新表,它将显示总值,平均值和最大值。
我必须将结果插入到该表中。
该表只有4行。没有任命,提前任命,任命迟到和任命准时。
所以......我......似的..
insert into newTable
select
'No Appointment' as 'Col1',
avg statement,
total statement,
max statement
from orgTable
where (general conditions) and (unique condition to check NO APPOINTMENT);
我必须为另外3行做同样的事情......其中只有不同的条件才能检查早期,准时或晚期......
所以......声明超长。
我想缩小尺寸..我怎样才能实现这一目标?
答案 0 :(得分:1)
真的不需要减小尺寸。 SQL语句可能会很长。
然而,一旦它运行,它就完成了。记录将在那里,你可以继续前进。
这是经常发生还是循环发生的事情?
答案 1 :(得分:1)
让我们来看你原来的陈述:
insert into newTable
select
'No Appointment' as 'Col1',
avg statement,
total statement,
max statement
from orgTable
where (general conditions) and (unique condition to check NO APPOINTMENT);
让我们希望unique condition to check <X>
很简单。我们可以将您的陈述改为:
insert into newTable
select
CASE
WHEN (unique condition to check NO APPOINTMENT) THEN 'No Appointment'
WHEN (unique condition to check APPOINTMENT EARLY) THEN 'Early'
WHEN (unique condition to check APPOINTMENT LATE) THEN 'Late'
WHEN (unique condition to check APPOINTMENT PUNCTUAL) THEN 'Punctual'
END as 'Col1',
avg statement,
total statement,
max statement
from orgTable
where (general conditions)
GROUP BY
CASE
WHEN (unique condition to check NO APPOINTMENT) THEN 'No Appointment'
WHEN (unique condition to check APPOINTMENT EARLY) THEN 'Early'
WHEN (unique condition to check APPOINTMENT LATE) THEN 'Late'
WHEN (unique condition to check APPOINTMENT PUNCTUAL) THEN 'Punctual'
END
如果这些条件看起来过于复杂,那么您可以将此case表达式移动到subselect语句中(即,您的from子句看起来像:
from (select col1,col2,col3,<case expression here> as Appointment from orgTable) t
然后,您就可以在Appointment
和SELECT
条款中引用GROUP BY
。
我假设orgTable
中的所有行都属于这4个约会类别中的一个。否则,您可能需要进一步过滤这些行。
答案 2 :(得分:1)
完整的概念验证(现在在Sql Server中),我们也使用CTE(WITH子句),因此我们不需要重复GROUP BY子句的特定条件;基本上程序的逻辑是首先标记它们所属的特定条件的行,然后从那里我们将它们分组到WITH子句之外。
-- drop table attendance;
-- drop table yourtable;
create table attendance
(
arrived datetime
);
declare @d datetime;
set @d = GETDATE();
declare @t integer;
set @t = 0;
while @t < 50 begin
insert into attendance select dateadd(hour, @t, @d);
set @t = @t + 1;
end
select * from attendance;
create table yourtable
(
segment varchar(max),
total int,
the_max datetime
);
with tagger as
(
select
-- specific conditions here
case
when DATEPART(hour,arrived) between 0 and 7 then
'First Shift'
when DATEPART(hour,arrived) between 8 and 15 then
'Second Shift'
when DATEPART(hour,arrived) between 16 and 23 then
'Third Shift'
else
'Hurry, inform the programmer of the anomaly!'
end
as segment,
*
from attendance
)
insert into yourtable(segment, total, the_max)
select segment, count(*), max(arrived)
from tagger
group by segment;
select * from yourtable