多列的大小写和总和

时间:2014-09-22 23:14:00

标签: sql

在我的数据库中,我有几千个客户,某些标准以不同的间隔发生。一周中的每一天都有列(M,Tu,W,Th,F,Sa,Su)。我需要查看每周会有多少天触发任务。我有下面的查询,但它当然也会返回一周中的特定日期以及每周的TotalDays。但是,我需要查看TotalDays,而不是每个日期都显示。我怎么能做到这一点?

SELECT X.*,M+Tu+W+Th+F+Sa+Su AS TotalDays
FROM
    (
    SELECT
        CASE WHEN [M] = '1' THEN 1 ELSE 0 END as "M",
        CASE WHEN [Tu] = '1' THEN 1 ELSE 0 END as  "Tu",
        CASE WHEN [W] = '1' THEN 1 ELSE 0 END as "W",
        CASE WHEN [Th] = '1' THEN 1 ELSE 0 END as  "Th",
        CASE WHEN [F] = '1' THEN 1 ELSE 0 END as "F",
        CASE WHEN [Sa] = '1' THEN 1 ELSE 0 END as  "Sa",
        CASE WHEN [Su] = '1' THEN 1 ELSE 0 END as "Su"
    FROM
        Customers
    ) X

我应该说这里的数据类型是位,所以我不能只做一个天数,如下所示,因为这会返回一个错误,数据类型位对于sum运算符是无效的。

SELECT 
 (SUM(M) + SUM(Tu) + SUM(W) + SUM(Th) + SUM(F) + SUM(Sa) + SUM(Su)) as TotalDays
FROM Customers

1 个答案:

答案 0 :(得分:5)

这是你想要的吗?

SELECT SUM(CASE WHEN [M] = '1' THEN 1 ELSE 0 END +
           CASE WHEN [Tu] = '1' THEN 1 ELSE 0 END +
           CASE WHEN [W] = '1' THEN 1 ELSE 0 END +
           CASE WHEN [Th] = '1' THEN 1 ELSE 0 END +
           CASE WHEN [F] = '1' THEN 1 ELSE 0 END +
           CASE WHEN [Sa] = '1' THEN 1 ELSE 0 END +
           CASE WHEN [Su] = '1' THEN 1 ELSE 0 END
          )
FROM Customers;