我有SQL Server查询,使用这个,我根据某些条件将事件id和列拆分为两列。查询执行成功,但结果不合适。它的一半有用。请帮助我得到预期的结果。我希望两个拆分列都有一行,而不是两行和空格。 SQL查询:
select convert(date, paymenttime)) , SUM(case when eventid = 33 then 1 ELSE 0 END) AS column1,
SUM(case when eventid = 36 then 1 ELSE 0 END) AS column2
from tbltransMain_backup where
paymentime <= '20160731' and PaymentTime >= '20160701'
group by convert(date,paymenttime),event_id
order by convert(date,paymenttime)
预期结果:
2016-07-01 27 1
2016-07-02 28 2
2016-07-03 30 15
答案 0 :(得分:1)
您在问题中发布的查询(可能是在不知不觉中)应该已经为您提供了所需的结果:
SELECT CONVERT(DATE, paymenttime),
SUM(CASE WHEN event_id = 33 THEN 1 ELSE 0 END) AS column1,
SUM(CASE WHEN event_id = 36 THEN 1 ELSE 0 END) AS column2
FROM tbltransMain_backup
WHERE paymentime <= '20160731' AND
paymentime >= '20160701'
GROUP BY CONVERT(DATE, paymenttime)
ORDER BY CONVERT(DATE, paymenttime)
每个日期获得两行的原因是您的查询具有以下分组:
GROUP BY CONVERT(DATE, paymenttime),
event_id
换句话说,每个日期都有两个组,一个用于event_id = 33
,另一个用于event_id = 36
。