【问题标题】:Transition from mySQL to msSQL Sum Query wont work从 mySQL 到 msSQL Sum Query 的转换不起作用
【发布时间】:2016-03-24 12:22:25
【问题描述】:

我一直在阅读多个论坛并到处寻找答案,但我似乎找不到与我遇到的问题相似的人。我们目前正在将数据库从 mySQL 迁移到 msSQL。我在 mySQL 中有一个查询,它非常适合我需要它做的事情,但我似乎无法在 msSQL 中弄清楚。我想要做的是显示有多少计算机将在某一年更换,有多少不符合条件,有多少正在进行中,有多少已完成,同时保持初始总数。这是我在 mySQL 中的内容

SELECT RefreshCycle, 
       Count(*) - sum(RefreshStatus = 'Not Eligible') as Total,
       sum(RefreshStatus = 'Completed') as 'Completed', 
       sum(RefreshStatus = 'Not Started') as 'Not Started', 
       sum(RefreshStatus = 'In Progress') as 'In Progress', 
       sum(RefreshStatus = 'Not Eligible') as 'Not Eligible' 
FROM [InventoryDatabase].[dbo].[Hardware_Inventory] 
group by RefreshCycle, RefreshStatus 
order by RefreshCycle asc; 

这给了我一个表格结果

目前我为数据库中的每个计算机条目都有名为 RefreshCycleRefreshStatus 的列,我需要能够执行此报告,我对此感到困惑,我不知道为什么 SQL 告诉我我有我的总和语法不正确。任何帮助将不胜感激

【问题讨论】:

    标签: mysql sql-server sum


    【解决方案1】:

    试试这个:

    SELECT RefreshCycle, 
           Count(*) - sum(CASE WHEN RefreshStatus = 'Not Eligible' THEN 1 ELSE 0 END) as Total,
           sum(CASE WHEN RefreshStatus = 'Completed' THEN 1 ELSE 0 END) as 'Completed', 
           sum(CASE WHEN RefreshStatus = 'Not Started' THEN 1 ELSE 0 END) as 'Not Started', 
           sum(CASE WHEN RefreshStatus = 'In Progress' THEN 1 ELSE 0 END) as 'In Progress', 
           sum(CASE WHEN RefreshStatus = 'Not Eligible' THEN 1 ELSE 0 END) as 'Not Eligible' 
    FROM [InventoryDatabase].[dbo].[Hardware_Inventory] 
    group by RefreshCycle 
    order by RefreshCycle;
    

    在 SQL Server 2012+ 中,这可以简化为:

    SELECT RefreshCycle, 
           Count(*) - sum(IIF(RefreshStatus = 'Not Eligible', 1, 0)) as Total,
           sum(IIF(RefreshStatus = 'Completed', 1, 0)) as 'Completed', 
           sum(IIF(RefreshStatus = 'Not Started', 1, 0)) as 'Not Started', 
           sum(IIF(RefreshStatus = 'In Progress', 1, 0)) as 'In Progress', 
           sum(IIF(RefreshStatus = 'Not Eligible', 1, 0)) as 'Not Eligible' 
    FROM [InventoryDatabase].[dbo].[Hardware_Inventory] 
    group by RefreshCycle 
    order by RefreshCycle;
    

    【讨论】:

    • SQL Server 2012 运行良好,非常感谢!
    • @GhislainJC 很高兴我能够提供帮助并欢迎来到 Stack Overflow。如果它帮助您解决问题,请将这个或任何其他答案标记为已接受。
    • 天哪,我在服务器 2012 中完成了所有过渡,但生产服务器最终变成了 2008 哈哈
    猜你喜欢
    • 2014-08-18
    • 2015-07-25
    • 1970-01-01
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-22
    • 1970-01-01
    相关资源
    最近更新 更多