如何计算特定行

时间:2017-04-17 10:50:25

标签: sql sql-server database

我的表包含Id,日期和状态,即打开/关闭 我只想在sql中得到一个结果,其中包含逐月开启,关闭和总数的Id 例如,在1月开放计数15,关闭计数5和总计数20

2 个答案:

答案 0 :(得分:0)

使用RollUp()和Group By,如下所示:

;WITH T AS
(
    SELECT
        Id,     
        DATENAME(MONTH,[Date]) AS [MonthName],          
        Status
    FROM @tblTest
)
SELECT
    [MonthName],
    [Status],
    StatusCount
FROM
(
    SELECT
        MonthName,
        CASE ISNULL(Status,'') WHEN '' THEN 'Total' ELSE Status END AS Status,          
        Count(Status) AS StatusCount                        
    FROM T
    GROUP BY ROLLUP([MonthName],[Status])
)X
WHERE X.MonthName IS NOT NULL
ORDER BY X.[MonthName],X.[Status]

<强>输出:

enter image description here

注意:如果按行逐行显示所需数据,则应用PIVOT

答案 1 :(得分:-1)

PollModel.findOneAndUpdate({"_id":req.session.pollId, "options.name": req.body.votedFor}, {$inc:{"options.$.voteCount":1} }, {new: true}, function(err, doc){
    if(err){
        console.log("Something wrong when updating data! "+err);
    }
    console.log(doc);
    res.send(doc);
  });