修改查询以根据特定列检查组内的多个值
Posted
技术标签:
【中文标题】修改查询以根据特定列检查组内的多个值【英文标题】:Amend Query To Check For Multiple Values Within A Group Based On Specific Column 【发布时间】:2019-08-02 09:57:38 【问题描述】:我有来自外部系统的下表(数据是匿名的):
我使用以下查询按列cola
、colb
和colc
的组合对结果进行分组;并且 case 语句将 weekday 列中的 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
分组时是否有多个阈值,根据下面的模型结果集:
请注意,cola
、colb
和 colc
组具有第二个阈值的所有行的 hasMultipleThreshold
列都为 TRUE,而不仅仅是一个不同的行。
如果确实可能的话,我不确定如何修改对此列的查询。任何指导表示赞赏。
【问题讨论】:
【参考方案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
【讨论】:
谢谢,但我收到以下错误Use of DISTINCT is not allowed with the OVER clause.
@JohnSteed,我已经修改了,你现在可以查看【参考方案2】:
你可以试试这个
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
【讨论】:
谢谢,但我收到以下错误Incorrect syntax near the keyword 'on'.
以上是关于修改查询以根据特定列检查组内的多个值的主要内容,如果未能解决你的问题,请参考以下文章