我有一个来自外部系统的下表(数据已匿名):
我使用以下查询将结果按列cola
,colb
和colc
的组合进行分组; case语句将工作日列中的x值替换为amount
列中的相应值。效果很好。
SELECT
cola,
colb,
colc,
max(case when Mon = 'x' THEN amount END) as Mon,
max(case when Tue = 'x' THEN amount END) as Tue,
max(case when Wed = 'x' THEN amount END) as Wed,
max(case when Thu = 'x' THEN amount END) as Thu,
max(case when Fri = 'x' THEN amount END) as Fri,
max(case when Sat = 'x' THEN amount END) as Sat,
max(case when Sun = 'x' THEN amount END) as Sun
FROM tbltestquote
GROUP BY
cola,
colb,
colc
结果是:
我现在添加了一个名为threshold
的新列。您可以看到,按cola
,colb
和colc
分组时,threshold
可以有多个值,如下所示:
我更新后的SQL查询(将这一新列考虑在内)是
SELECT
cola,
colb,
colc,
threshold,
max(case when Mon = 'x' THEN amount END) as Mon,
max(case when Tue = 'x' THEN amount END) as Tue,
max(case when Wed = 'x' THEN amount END) as Wed,
max(case when Thu = 'x' THEN amount END) as Thu,
max(case when Fri = 'x' THEN amount END) as Fri,
max(case when Sat = 'x' THEN amount END) as Sat,
max(case when Sun = 'x' THEN amount END) as Sun
FROM tbltestquote
GROUP BY
cola,
colb,
colc,
threshold
然后返回带有两个新行的以下结果集,这是正确的:
我现在想添加一个新的布尔列,该列指示根据以下模型结果设置,在按cola
,colb
和colc
分组时是否存在多个阈值:< / p>
请注意,对于hasMultipleThreshold
,cola
和colb
组具有第二阈值的所有行,colc
列均为TRUE,而不仅仅是另一行。
如果确实可行,我不确定如何修改此列的查询。任何指导表示赞赏。
答案 0 :(得分:1)
您可以在下面尝试-
SELECT
cola,
colb,
colc,
threshold,
max(case when Mon = 'x' THEN amount END) as Mon,
max(case when Tue = 'x' THEN amount END) as Tue,
max(case when Wed = 'x' THEN amount END) as Wed,
max(case when Thu = 'x' THEN amount END) as Thu,
max(case when Fri = 'x' THEN amount END) as Fri,
max(case when Sat = 'x' THEN amount END) as Sat,
max(case when Sun = 'x' THEN amount END) as Sun,
case when count(*) over(partition by cola,colb,colc order by cola)>1 then 1 else 0 end as hasMultipleThreshold
FROM tbltestquote a
GROUP BY
cola,
colb,
colc,
threshold
答案 1 :(得分:0)
您可以尝试
SELECT
cola,
colb,
colc,
threshold,
max(case when Mon = 'x' THEN amount END) as Mon,
max(case when Tue = 'x' THEN amount END) as Tue,
max(case when Wed = 'x' THEN amount END) as Wed,
max(case when Thu = 'x' THEN amount END) as Thu,
max(case when Fri = 'x' THEN amount END) as Fri,
max(case when Sat = 'x' THEN amount END) as Sat,
max(case when Sun = 'x' THEN amount END) as Sun,
( select case
when count(threshold)>0
then cast(1 as bit)
else
cast(0 as bit)
end
from tbltestquote as ts where ts.cola=t.cola and ts.colb=t.colb and ts.colc= t.colc
group by ts.cola, ts.colb, ts.colc, ts.threshold ) as hasMultipleThreshold
FROM tbltestquote as t
GROUP BY
cola,
colb,
colc,
threshold