SELECT语句中的部分不需要翻译。

huangapple go评论52阅读模式
英文:

SELECT records from a GROUP BY where string in field is 'I1' and there are no records in the GROUP BY with string 'H4'

问题

SELECT
SUBSTRING(Ref,1,9) AS LRN,
MessageType
FROM table1 dh
WHERE MessageType IN ('I1', 'H4')
GROUP BY SUBSTRING(Ref,1,9),MessageType
HAVING MessageType = 'I1' AND NOT MessageType = 'H4'
英文:

I have a data table that looks as below. I need to select records GROUPED by ref field where MessageType field is 'I1' but no records in the GROUP are MessageType 'H4'. I'm not a pro on SQL so I'm sure my code is laughable but bare with me. Also the Ref may have /001 on the end some times so I need to use SUBSTRING in the Select and GROUP BY. So in the below table I need only REF2_ABCD to be selected as it has MessageType I1 but not another record that is MessageType H4

[Table]

Ref MessageType
REF1_ABCD I1
REF1_ABCD/001 H4
REF2_ABCD I1

[/table]

SELECT
SUBSTRING(Ref,1,9) AS LRN,
MessageType
FROM table1 dh
WHERE MessageType IN ('I1', 'H4')
GROUP BY SUBSTRING(Ref,1,9),MessageType
HAVING MessageType = 'I1' AND NOT MessageType = 'H4'

答案1

得分: 1

Having 可用于对聚合结果进行筛选。在这种情况下,我认为你不需要它。

SELECT
SUBSTRING(Ref,1,9) AS LRN,
MessageType
FROM table1 dh
WHERE MessageType IN ('I1')
  AND NOT EXISTS (SELECT 1 
                  FROM table1 t 
                  WHERE t.MessageType = 'H4' 
                   and SUBSTRING(t.Ref,1,9) = SUBSTRING(dh.Ref,1,9))
GROUP BY SUBSTRING(Ref,1,9),MessageType

注:如果需要/希望,可以将 MessageType IN ('I1') 编写为 MessageType = 'I1'

英文:

Having can be used to filter on aggregated results. In this case, I think, you do not need it.

SELECT
SUBSTRING(Ref,1,9) AS LRN,
MessageType
FROM table1 dh
WHERE MessageType IN ('I1')
  AND NOT EXISTS (SELECT 1 
                  FROM table1 t 
                  WHERE t.MessageType = 'H4' 
                   and SUBSTRING(t.Ref,1,9) = SUBSTRING(dh.Ref,1,9))
GROUP BY SUBSTRING(Ref,1,9),MessageType

Note: MessageType IN ('I1') can, if needed/wanted, be written as MessageType = 'I1'

答案2

得分: 0

尝试这个:

SELECT
SUBSTRING(Ref,1,9) AS LRN
FROM table1 dh
WHERE MessageType not IN ('H4')
GROUP BY LRN

或者如果你需要两个字段作为输出:

SELECT
SUBSTRING(Ref,1,9) AS LRN, messagetype
FROM table1 dh
WHERE MessageType not IN ('H4')
GROUP BY LRN, messagetype
英文:

Try this one:

SELECT
SUBSTRING(Ref,1,9) AS LRN
FROM table1 dh
WHERE MessageType not IN ('H4')
GROUP LRN

or if you need 2 fields in output:

SELECT
SUBSTRING(Ref,1,9) AS LRN, messagetype
FROM table1 dh
WHERE MessageType not IN ('H4')
GROUP LRN, messagetype

huangapple
  • 本文由 发表于 2023年2月19日 02:54:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/75495662.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定