我有以下查询:
SELECT
Sender,
DATEADD(dd, DATEDIFF(dd, 0, Date_Reported) / 7 * 7, 0) AS Weekdate,
COUNT(status) AS TranCount
FROM
tx
WHERE
customer = 'ABC'
AND DATEADD(dd, DATEDIFF(dd, 0, Date_Reported) / 7 * 7, 0) >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) / 7 * 7, 0)
AND DATEADD(dd, DATEDIFF(dd, 0, Date_Reported) / 7 * 7, 0) < DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
GROUP BY
Sender, DATEADD(dd,DATEDIFF(dd,0,Date_Reported)/7 * 7,0)
这将返回每个发件人的所有交易的列表。我想要的只有两行,包括两种发件人类型-一种是sender = "AA"
,另一种是sender NOT IN "AA"
。
如何将其合并到脚本中?目前,我收到了50个发件人的列表,但我只想如上所述2个发件人
预期结果
Sender | Weekdate | TranCount
AA | 25/06/2018 | 33
"Not Sender AA" | 25/06/2018 | 26
答案 0 :(得分:2)
使用简单的CASE语句:
SELECT
CASE Sender WHEN 'AA' THEN Sender ELSE 'Not Sender AA' END AS Sender,
DATEADD(dd, DATEDIFF(dd, 0, Date_Reported) / 7 * 7, 0) AS Weekdate,
COUNT(status) AS TranCount
FROM
tx
WHERE
customer = 'ABC'
AND DATEADD(dd, DATEDIFF(dd, 0, Date_Reported) / 7 * 7, 0) >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) / 7 * 7, 0)
AND DATEADD(dd, DATEDIFF(dd, 0, Date_Reported) / 7 * 7, 0) < DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
GROUP BY
CASE Sender WHEN 'AA' THEN Sender ELSE 'Not Sender AA' END, DATEADD(dd,DATEDIFF(dd,0,Date_Reported)/7 * 7,0)
请注意,您必须在GROUP BY子句中放入相同的CASE语句。
答案 1 :(得分:1)
工会呢? 诸如此类(很抱歉,那里没有MS SQL Studio)
SELECT
Sender,
DATEADD(dd, DATEDIFF(dd, 0, Date_Reported) / 7 * 7, 0) AS Weekdate,
COUNT(status) AS TranCount
FROM
tx
WHERE
sender = 'AA' and
customer = 'ABC'
AND DATEADD(dd, DATEDIFF(dd, 0, Date_Reported) / 7 * 7, 0) >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) / 7 * 7, 0)
AND DATEADD(dd, DATEDIFF(dd, 0, Date_Reported) / 7 * 7, 0) < DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
GROUP BY
Sender, DATEADD(dd,DATEDIFF(dd,0,Date_Reported)/7 * 7,0)
union
SELECT
'Not Sender AA',
DATEADD(dd, DATEDIFF(dd, 0, Date_Reported) / 7 * 7, 0) AS Weekdate,
COUNT(status) AS TranCount
FROM
tx
WHERE
Sender <> 'AA' and
customer = 'ABC'
AND DATEADD(dd, DATEDIFF(dd, 0, Date_Reported) / 7 * 7, 0) >= DATEADD(dd, DATEDIFF(dd, 0, GETDATE()) / 7 * 7, 0)
AND DATEADD(dd, DATEDIFF(dd, 0, Date_Reported) / 7 * 7, 0) < DATEADD(dd, DATEDIFF(dd, 0, GETDATE()), 0)
GROUP BY
DATEADD(dd,DATEDIFF(dd,0,Date_Reported)/7 * 7,0)