首页 \ 问答 \ 计算Total vote as subtractive upvote downvote with group by conditon in mysql(Calculate Total vote as subtractive upvote to downvote with group by conditon in mysql)

计算Total vote as subtractive upvote downvote with group by conditon in mysql(Calculate Total vote as subtractive upvote to downvote with group by conditon in mysql)

Database table: 
+----------------------------------------------+
| vote_id | user_id | vote_type | fieldset_id  |
+----------------------------------------------+
|   1     |  1      |  up       |  111         |
|   2     |  2      |  up       |  111         |
|   3     |  3      |  down     |  111         |
|   4     |  4      |  up       |  111         |
+----------------------------------------------+

Mysql查询:

select vote_type,count(vote_type) as total_vote 
   from vote_mst 
   where fieldset_id='111' 
   group by vote_type

预期产出: +3

而我越来越

+-------------------------+
| vote_type  | total_vote |
+-------------------------+
|   up       |  3         |
|   down     |  1         |
+-------------------------+

如在Mysql查询中计算(Upvote-Downvote)


Database table: 
+----------------------------------------------+
| vote_id | user_id | vote_type | fieldset_id  |
+----------------------------------------------+
|   1     |  1      |  up       |  111         |
|   2     |  2      |  up       |  111         |
|   3     |  3      |  down     |  111         |
|   4     |  4      |  up       |  111         |
+----------------------------------------------+

Mysql Query:

select vote_type,count(vote_type) as total_vote 
   from vote_mst 
   where fieldset_id='111' 
   group by vote_type

Expected Output: +3

While i am getting

+-------------------------+
| vote_type  | total_vote |
+-------------------------+
|   up       |  3         |
|   down     |  1         |
+-------------------------+

as calculating (Upvote-Downvote) inside MysQL Query


原文:https://stackoverflow.com/questions/43573180
更新时间:2022-01-26 06:01

最满意答案

这是创建.NET的人的决定。 枚举由另一个值类型( intshortbyte等)支持,因此它实际上可以具有对这些值类型有效的任何值。

我个人并不喜欢它的工作方式,因此我制作了一系列实用方法:

/// <summary>
/// Utility methods for enum values. This static type will fail to initialize 
/// (throwing a <see cref="TypeInitializationException"/>) if
/// you try to provide a value that is not an enum.
/// </summary>
/// <typeparam name="T">An enum type. </typeparam>
public static class EnumUtil<T>
    where T : struct, IConvertible // Try to get as much of a static check as we can.
{
    // The .NET framework doesn't provide a compile-checked
    // way to ensure that a type is an enum, so we have to check when the type
    // is statically invoked.
    static EnumUtil()
    {
        // Throw Exception on static initialization if the given type isn't an enum.
        Require.That(typeof (T).IsEnum, () => typeof(T).FullName + " is not an enum type.");
    }

    /// <summary>
    /// In the .NET Framework, objects can be cast to enum values which are not
    /// defined for their type. This method provides a simple fail-fast check
    /// that the enum value is defined, and creates a cast at the same time.
    /// Cast the given value as the given enum type.
    /// Throw an exception if the value is not defined for the given enum type.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="enumValue"></param>
    /// <exception cref="InvalidCastException">
    /// If the given value is not a defined value of the enum type.
    /// </exception>
    /// <returns></returns>
    public static T DefinedCast(object enumValue)

    {
        if (!System.Enum.IsDefined(typeof(T), enumValue))
            throw new InvalidCastException(enumValue + " is not a defined value for enum type " +
                                           typeof (T).FullName);
        return (T) enumValue;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="enumValue"></param>
    /// <returns></returns>
    public static T Parse(string enumValue)
    {
        var parsedValue = (T)System.Enum.Parse(typeof (T), enumValue);
        //Require that the parsed value is defined
        Require.That(parsedValue.IsDefined(), 
            () => new ArgumentException(string.Format("{0} is not a defined value for enum type {1}", 
                enumValue, typeof(T).FullName)));
        return parsedValue;
    }

    public static bool IsDefined(T enumValue)
    {
        return System.Enum.IsDefined(typeof (T), enumValue);
    }

}

public static class EnumExtensions
{
    public static bool IsDefined<T>(this T enumValue)
        where T : struct, IConvertible
    {
        return EnumUtil<T>.IsDefined(enumValue);
    }
}

这样,我可以说:

if(!sEnum.IsDefined()) throw new Exception(...);

... 要么:

EnumUtil<Stooge>.Parse(s); // throws an exception if s is not a defined value.

This was a decision on the part of the people who created .NET. An enum is backed by another value type (int, short, byte, etc), and so it can actually have any value that is valid for those value types.

I personally am not a fan of the way this works, so I made a series of utility methods:

/// <summary>
/// Utility methods for enum values. This static type will fail to initialize 
/// (throwing a <see cref="TypeInitializationException"/>) if
/// you try to provide a value that is not an enum.
/// </summary>
/// <typeparam name="T">An enum type. </typeparam>
public static class EnumUtil<T>
    where T : struct, IConvertible // Try to get as much of a static check as we can.
{
    // The .NET framework doesn't provide a compile-checked
    // way to ensure that a type is an enum, so we have to check when the type
    // is statically invoked.
    static EnumUtil()
    {
        // Throw Exception on static initialization if the given type isn't an enum.
        Require.That(typeof (T).IsEnum, () => typeof(T).FullName + " is not an enum type.");
    }

    /// <summary>
    /// In the .NET Framework, objects can be cast to enum values which are not
    /// defined for their type. This method provides a simple fail-fast check
    /// that the enum value is defined, and creates a cast at the same time.
    /// Cast the given value as the given enum type.
    /// Throw an exception if the value is not defined for the given enum type.
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="enumValue"></param>
    /// <exception cref="InvalidCastException">
    /// If the given value is not a defined value of the enum type.
    /// </exception>
    /// <returns></returns>
    public static T DefinedCast(object enumValue)

    {
        if (!System.Enum.IsDefined(typeof(T), enumValue))
            throw new InvalidCastException(enumValue + " is not a defined value for enum type " +
                                           typeof (T).FullName);
        return (T) enumValue;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="enumValue"></param>
    /// <returns></returns>
    public static T Parse(string enumValue)
    {
        var parsedValue = (T)System.Enum.Parse(typeof (T), enumValue);
        //Require that the parsed value is defined
        Require.That(parsedValue.IsDefined(), 
            () => new ArgumentException(string.Format("{0} is not a defined value for enum type {1}", 
                enumValue, typeof(T).FullName)));
        return parsedValue;
    }

    public static bool IsDefined(T enumValue)
    {
        return System.Enum.IsDefined(typeof (T), enumValue);
    }

}

public static class EnumExtensions
{
    public static bool IsDefined<T>(this T enumValue)
        where T : struct, IConvertible
    {
        return EnumUtil<T>.IsDefined(enumValue);
    }
}

This way, I can say:

if(!sEnum.IsDefined()) throw new Exception(...);

... or:

EnumUtil<Stooge>.Parse(s); // throws an exception if s is not a defined value.

Update

As Brandon Kramer pointed out in the comments, C# 7.3 introduced some new generic types that allow the where T : struct, IConvertible above to be replaced with where T : Enum, to get better compile-time checking of the Enum-ness of the type being passed in. That way you can get rid of the guard statement in EnumUtil's static constructor.

相关问答

更多
  • 我经常为它做一个通用的帮手: public static T ParseEnum(string value) where T:struct { return (T)Enum.Parse(typeof(T), value); } 您可以将它与Jon Skeet的 Unstrained Melody (或其他任何后处理IL处理器)结合使用,以在枚举上获得适当的类型约束,但这是可选的。 那么你可以像这样使用它: var enumValue = ParseEnum(iUserTy ...
  • 可悲的是,没有一个很好的解决方案,你想要使用枚举。 您还可以尝试其他选项,例如特定“枚举”类型的一系列public static readonly字段: public class CardSuit { public static readonly CardSuit Spades = new CardSuit(); public static readonly CardSuit Hearts = new CardSuit(); ... } public enum GameSuit ...
  • 正如一些评论所说,除了一些简单的情况外,用Regular Expression解析源文件可能不是一个好主意 例如这个源文件,来自: http : //en.cppreference.com/w/cpp/language/enum #include // enum that takes 16 bits enum smallenum: int16_t { a, b, c }; // color may be red (value 0), yellow (val ...
  • 我在这里找到了解决方案(nkukushkin的回答)。 问题 我认为这是一个编译顺序问题,但认为Xcode会自动处理它。 因此我甚至懒得去我的项目设置。 事实证明,它可能并不总是如此。 怎么解决 选择你的项目, 选择你的目标, 转到目标的Build Phases , 扩展Compile Sources 。 在这里,您将看到项目中正在编译的文件列表。 在我的例子中,我最初定义的文件enum sectionObject列在我扩展枚举的文件下。 因此,我必须将定义文件移到顶部,以便扩展程序可以看到它。 不幸的是, ...
  • 重新编写示例代码: System.Type t = service.BusinessObjectEnumeration.GetType(); service.SomeField = Enum.Parse(t,"Item1"); 也许这样做的方式是通过反思: var prop = service.GetType().GetProperty("SomeField"); prop.SetValue(service, Enum.Parse(prop.PropertyType, "Item1"), null); ...
  • 您还需要指定值: [Flags] public enum EqualityOperator { Equal = 0, NotEqual = 1, LessThan = 2, LessThanOrEqual = 4, GreaterThan = 8, GreaterThanOrEqual = 16, Like = 32, NotLike = 64, In = 128, NotIn = 256 } Like解析为LessThan ...
  • 这是创建.NET的人的决定。 枚举由另一个值类型( int , short , byte等)支持,因此它实际上可以具有对这些值类型有效的任何值。 我个人并不喜欢它的工作方式,因此我制作了一系列实用方法: /// /// Utility methods for enum values. This static type will fail to initialize /// (throwing a ) if ...
  • enums的调试信息与lldb搜索符号的模式之间存在不匹配,如果未指定枚举名称,则搜索特定的枚举值会非常昂贵。 目前,如果其他一些操作没有导致enum调试信息被引入,lldb将不会找到它。 不幸的是,NSStringEncoding枚举是一个匿名枚举,所以不可能通过name :: value指定一个值。 但是,如果您使用Xcode 7.x,则可以将基础模块导入到lldb用于表达式解析的编译器中: (lldb) expr @import Foundation 然后lldb会找到这个枚举值(以及许多其他的东西 ...
  • 你可以试试像 string enumString = "Date|Reported"; UserFilter uf = enumString.Split('|').ToList().Select(e => { UserFilter u; Enum.TryParse(e, true, out u); return u; }).Aggregate((u, c) => u = u | c); 但是我会建议你将你的枚举改为 public enum UserFilter { None ...
  • 只需使用Enum.IsDefined 。 基本上枚举只是整数,你可以将任何int分配给枚举,即使它没有定义。 if(!Enum.IsDefined(typeof(A), a)) { throw new InvalidCastException("Not a valid value for A: " + a); } Just use Enum.IsDefined. Basically enums are just ints and you can assign any int to an enum ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)