sql值和对

63lcw9qa  于 2021-06-27  发布在  Hive
关注(0)|答案(2)|浏览(344)

我是sql新手,不知道怎么做。我想对类似的配对(vin,action)求一个名为“total\u spending”的coulmn的和,然后选择第一个经销商名称和参考月份年份(这样就不会产生重复项),并有一个输出,如示例:input

  1. action dealer_name vin Total_spending reference month year
  2. A1 D1 V1 T1 R1 M1 Y1
  3. A2 D2 V2 T2 R1 M1 Y1
  4. A2 D2 V2 T3 R2 M2 Y2
  5. A3 D2 V1 T4 R1 M1 Y1
  6. A4 D1 V2 T5 R1 M1 Y1
  7. A2 D1 V2 T6 R1 M1 Y1
  8. A1 D1 V1 T7 R2 M2 Y2
  9. A4 D1 V2 T8 R2 M2 Y2
  10. A1 D1 V1 T9 R3 M3 Y3
  11. A3 D2 V2 T10 R1 M1 Y1
  12. A3 D2 V1 T11 R2 M2 Y2

输出

  1. action dealer_name vin Total_spending reference month year
  2. A1 D1 V1 T1 + T7 + T9 R1 M1 Y1
  3. A2 D2 V2 T2 + T3 R1 M1 Y1
  4. A3 D2 V1 T4 + T11 R1 M1 Y1
  5. A4 D1 V2 T5 + T8 R1 M1 Y1
  6. A2 D1 V2 T6 R1 M1 Y1
  7. A3 D2 V2 T10 R1 M1 Y1
  8. SELECT
  9. action,
  10. dealer_name,
  11. vin,
  12. SUM(total_spending) as total_spending,
  13. reference,
  14. year,
  15. issue_date,
  16. country_code
  17. FROM
  18. db_raw_irn_67634_vdt.sap_vme_pol
  19. GROUP BY
  20. action,
  21. dealer_name,
  22. vin,
  23. reference,
  24. year,
  25. issue_date,
  26. country_code
laawzig2

laawzig21#

如果您的rdbms支持窗口函数,那么您可以执行一个窗口 SUM() 使用 ROW_NUMBER() 选择要显示的相关记录:

  1. SELECT
  2. action,
  3. dealer_name,
  4. vin,
  5. total_spending,
  6. reference,
  7. month,
  8. year
  9. FROM (
  10. SELECT
  11. action,
  12. dealer_name,
  13. vin,
  14. SUM(total_spending) OVER(PARTITION BY action, dealer_name, vin) total_spending,
  15. ROW_NUMBER() OVER(PARTITION BY action, dealer, vin ORDER BY reference, year, month) rn,
  16. reference,
  17. month,
  18. year
  19. FROM mytable
  20. ) x
  21. WHERE rn = 1
展开查看全部
vuv7lop3

vuv7lop32#

  1. SELECT action
  2. ,dealer_name
  3. ,vin
  4. ,SUM(total_spending)
  5. ,MIN(reference)
  6. ,MIN(month)
  7. ,MIN(YEAR)
  8. FROM db_raw_irn_67634_vdt.sap_vme_pol
  9. GROUP BY action
  10. ,dealer_name
  11. ,vin

相关问题