2

我在创建 sql 查询时遇到问题。我有一张表,其中包含列和数据:

ID COL1 COL2 COL3 COL4 COL5 COL6 COL7 
1 FGA DSA 2018-01-01 DB1 7999 1 0
2 FGA DSA 2018-01-01 DB1 6999 0 0
3 FGA DSA 2018-01-01 DB2 5999 1 1

我有一个查询:

SELECT t.COL3, t.COL1, t.COL2, STRING_AGG (c.COL4, ','), min(c.COL5)
FROM Offers as t
JOIN Offers as c on t.Id = c.Id
where t.COL3 between '2017-12-01' and '2017-12-31'
and t.COL1='FGA'
GROUP BY t.COL3, t.COL1, t.COL2

但是对于 STRING_AGG (c.COL4, ',') 我需要不同的值,对于 min(c.COL5) 我需要条件'其中 COL6 = 1'。我怎样才能做到这一点?

4

1 回答 1

2

STRING_AGG()(还)不支持DISTINCT. 您可以使用条件聚合做您想做的事情:

SELECT t.COL3, t.COL1, t.COL2,
       STRING_AGG(CASE WHEN seqnum = 1 THEN c.COL4 END, ','), 
       MIN(CASE WHEN c.col6 = 1 THEN c.COL5 END)
FROM (SELECT t.COL1, t.COL2, t.COL3, c.COL4, c.COL5, c.col6,
             ROW_NUMBER() OVER (PARTITION BY t.COL3, t.COL1, t.COL2, t.COL4 ORDER BY c.COL4) as seqnum
      FROM Offers t JOIN
           Offers c 
           ON t.Id = c.Id
      WHERE t.GenerationId = 1 AND
            t.COL3 between '2017-12-01' and '2017-12-31' AND
            t.COL1 = 'FGA'
      GROUP BY t.COL3, t.COL1, t.COL2
     ) to
GROUP BY t.COL3, t.COL1, t.COL2;

请注意使用ROW_NUMBER()来标识 的第一个值COL4,然后将其用于DISTINCT

于 2017-12-02T12:51:30.200 回答