修改查询以基于特定列检查组中的多个值

时间:2019-08-02 09:57:38

标签: sql sql-server tsql

我有一个来自外部系统的下表(数据已匿名):

enter image description here

我使用以下查询将结果按列colacolbcolc的组合进行分组; 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

结果是:

enter image description here

我现在添加了一个名为threshold的新列。您可以看到,按colacolbcolc分组时,threshold可以有多个值,如下所示:

enter image description here

我更新后的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

然后返回带有两个新行的以下结果集,这是正确的:

enter image description here

我现在想添加一个新的布尔列,该列指示根据以下模型结果设置,在按colacolbcolc分组时是否存在多个阈值:< / p>

enter image description here

请注意,对于hasMultipleThresholdcolacolb组具有第二阈值的所有行,colc列均为TRUE,而不仅仅是另一行。

如果确实可行,我不确定如何修改此列的查询。任何指导表示赞赏。

2 个答案:

答案 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