内部连接与枢轴条件sql

时间:2017-10-17 02:42:27

标签: mysql sql-server

我目前有以下sql查询:

SELECT  
  name,
  SUM( IF( MONTH(date) = 1, amount, 0) ) AS jan,
  SUM( IF( MONTH(date) = 2, amount, 0) ) AS feb,
  SUM( IF( MONTH(date) = 3, amount, 0) ) AS mar,
  SUM( IF( MONTH(date) = 4, amount, 0) ) AS apr,
  SUM( IF( MONTH(date) = 5, amount, 0) ) AS mei,
  SUM( IF( MONTH(date) = 6, amount, 0) ) AS jun,
  SUM( IF( MONTH(date) = 7, amount, 0) ) AS jul,
  SUM( IF( MONTH(date) = 8, amount, 0) ) AS agu,
  SUM( IF( MONTH(date) = 9, amount, 0) ) AS sep,
  SUM( IF( MONTH(date) = 10, amount, 0) ) AS okt,
  SUM( IF( MONTH(date) = 11, amount, 0) ) AS nov,
  SUM( IF( MONTH(date) = 12, amount, 0) ) AS des,
  SUM( amount ) AS total 
FROM iuran_detail 
WHERE (
  date BETWEEN '$date_first' AND '$date_last'
) GROUP BY name;

我希望用2个表sql,用户表(以及组)和数量进行修改。

enter image description here

我想结合内部联接或其他方式,以获得以下结果(例如,通过组A):

enter image description here

感谢

1 个答案:

答案 0 :(得分:1)

注意:如果连接表,最佳做法是使用源表名称或通过给予源表的别名为每个列引用添加前缀(我使用后者)。 “date”是一个糟糕的列名,因为它也被SQL本身使用并且可能引起混淆,所以下面我使用MySQL反引号来引用该列,在SQL-Server中你可以使用{{ 1}}而不是。

SELECT  
  u.name,
  SUM( IF( MONTH(`date`) = 1, d.amount, 0) ) AS jan,
  SUM( IF( MONTH(`date`) = 2, d.amount, 0) ) AS feb,
  SUM( IF( MONTH(`date`) = 3, d.amount, 0) ) AS mar,
  SUM( IF( MONTH(`date`) = 4, d.amount, 0) ) AS apr,
  SUM( IF( MONTH(`date`) = 5, d.amount, 0) ) AS mei,
  SUM( IF( MONTH(`date`) = 6, d.amount, 0) ) AS jun,
  SUM( IF( MONTH(`date`) = 7, d.amount, 0) ) AS jul,
  SUM( IF( MONTH(`date`) = 8, d.amount, 0) ) AS agu,
  SUM( IF( MONTH(`date`) = 9, d.amount, 0) ) AS sep,
  SUM( IF( MONTH(`date`) = 10, d.amount, 0) ) AS okt,
  SUM( IF( MONTH(`date`) = 11, d.amount, 0) ) AS nov,
  SUM( IF( MONTH(`date`) = 12, d.amount, 0) ) AS des,
  SUM( d.amount ) AS total 
FROM table_trx d
INNER JOIN table_user u on d.user_id = u.id
WHERE (
  d.`date` BETWEEN '$`date`_first' AND '$`date`_last'
) GROUP BY u.name;

我个人不喜欢使用IF()作为更标准的CASE表达式的替代,因为它在SQL数据库中得到了更广泛的支持。

SELECT  
  u.name,
  SUM( case when MONTH(`date`) = 1 then d.amount else 0 end ) AS jan,
  SUM( case when MONTH(`date`) = 2 then d.amount else 0 end ) AS feb,
  SUM( case when MONTH(`date`) = 3 then d.amount else 0 end ) AS mar,
  SUM( case when MONTH(`date`) = 4 then d.amount else 0 end ) AS apr,
  SUM( case when MONTH(`date`) = 5 then d.amount else 0 end ) AS mei,
  SUM( case when MONTH(`date`) = 6 then d.amount else 0 end ) AS jun,
  SUM( case when MONTH(`date`) = 7 then d.amount else 0 end ) AS jul,
  SUM( case when MONTH(`date`) = 8 then d.amount else 0 end ) AS agu,
  SUM( case when MONTH(`date`) = 9 then d.amount else 0 end ) AS sep,
  SUM( case when MONTH(`date`) = 10 then d.amount else 0 end ) AS okt,
  SUM( case when MONTH(`date`) = 11 then d.amount else 0 end ) AS nov,
  SUM( case when MONTH(`date`) = 12 then d.amount else 0 end ) AS des,
  SUM( d.amount ) AS total 
FROM table_trx d
INNER JOIN table_user u on d.user_id = u.id
WHERE (
  d.`date` BETWEEN '$`date`_first' AND '$`date`_last'
) GROUP BY u.name;