我可以在SQL中组合查询吗?我想获得一个总收入数字。这是我的查询

时间:2015-11-27 18:48:04

标签: sql sum

我的项目是学校的停车系统。为了获得总收入,我将总结许可价格列:

select sum(permit.price) from permit; 

然后,为了获得总违规收入,我将获得每种违规类型的票价(1),然后乘以违规类型的数量(2,3和4)

  1. select sum(violation_type.amount_due) from violation_type where violation_type_id = 1;
    
  2. select count(Violation_Type_ID = '1') from violation where violation_type_id = '1';
    
  3. select count(Violation_Type_ID = '2') from violation where violation_type_id = '2';
    
  4. select count(Violation_Type_ID = '3') from violation where violation_type_id = '3';
    
  5. select count(Violation_Type_ID = '4') from violation where violation_type_id = '4';
    
  6. 如何将所有这些放在1个查询中?感谢。

2 个答案:

答案 0 :(得分:0)

SELECT
    SUM(CASE
        WHEN vt.violation_type_id = '1' THEN 1
        ELSE 0
    END) ViolationType1Count,
    SUM(CASE
        WHEN vt.violation_type_id = '1' THEN vt.amount_due
        ELSE 0.0
    END) ViolationType1AmtDue,
    SUM(CASE
        WHEN vt.violation_type_id = '2' THEN 1
        ELSE 0
    END) ViolationType2Count,
    SUM(CASE
        WHEN vt.violation_type_id = '2' THEN vt.amount_due
        ELSE 0.0
    END) ViolationType2AmtDue,
    etc.
FROM
    violation_type vt INNER JOIN
        violation v
    ON vt.violation_type_id = v.violation_type_id

答案 1 :(得分:0)

如果你想在SQL中总结一切,那么:

SELECT SUM(TotalAmount) AS TotalAmount
FROM (
      SELECT SUM(permit.price) AS TotalAmount 
      FROM permit

      UNION ALL

      SELECT SUM(vt.amount_due)
      FROM violation v
      JOIN violation_type vt
      ON v.violation_type_id = vt.violation_type_id

    ) as Sums

如果您需要按违规类型细分,那么它将是:

          SELECT v.violation_type,
          COUNT() [Count], 
          SUM(vt.amount_due) TotalAmount
          FROM violation v
          JOIN violation_type vt
          ON v.violation_type_id = vt.violation_type_id
          GROUP ON v.violation_type

如果一个vio_type_id是一个varchar而不是一个数字,那么你会加入如下:

     ON CAST(v.violation_type_id AS INT) = vt.violation_type_id