SQL - 分组到单独的列

时间:2013-05-01 23:38:00

标签: sql sql-server sql-server-2008 group-by

使用SQL Server 2008 R2。我不确定这是否可行,但我想将两列分组并将它们的差异放在新列中。用一个例子解释可能更容易:

BEFORE::

[DATE]      [ID]                                  [AMT] [TYPE]
2013-01-11  36374DCD-47FE-48D8-8E70-8D3B37385311    2   20
2013-01-11  36374DCD-47FE-48D8-8E70-8D3B37385311    10  21
2013-01-11  4434E2D5-1D08-45FA-AADF-F653BF9A0D97    4   20
2013-01-11  4434E2D5-1D08-45FA-AADF-F653BF9A0D97    4   21

AFTER::

[DATE]      [ID]                                 [AMT 20] [AMT 21]
2013-01-11  36374DCD-47FE-48D8-8E70-8D3B37385311    2       10
2013-01-11  4434E2D5-1D08-45FA-AADF-F653BF9A0D97    4       4


这是我到目前为止的SQL:

SELECT 
    CAST(TransDate AS DATE) AS [TransDate],ItemID,COUNT(TransactionTypeID) AS [TransAmt], TransactionTypeID
FROM 
    Transactions
WHERE 
    TransDate BETWEEN '2013-01-01 10:00:00' AND '2013-02-01 10:00:00'
    AND TransactionTypeID IN (20,21)
GROUP BY
    CAST(TransDate AS DATE),ItemID,TransactionTypeID

感谢任何帮助,谢谢!

2 个答案:

答案 0 :(得分:1)

bluefeet回答可能是最好的方法,但如果你的查询变得更复杂,你可以随时使用尽可能多的UNIONS:)

    SELECT 
        CAST(TransDate AS DATE) AS [TransDate],ItemID,COUNT(TransactionTypeID) AS [TransAmt], TransactionTypeID
    FROM 
        Transactions
    WHERE 
        TransDate BETWEEN '2013-01-01 10:00:00' AND '2013-02-01 10:00:00'
        AND TransactionTypeID IN (20)
    GROUP BY
        CAST(TransDate AS DATE),ItemID,TransactionTypeID
UNION
SELECT 
    CAST(TransDate AS DATE) AS [TransDate],ItemID,COUNT(TransactionTypeID) AS [TransAmt], TransactionTypeID
FROM 
    Transactions
WHERE 
    TransDate BETWEEN '2013-01-01 10:00:00' AND '2013-02-01 10:00:00'
    AND TransactionTypeID IN (21)
GROUP BY
    CAST(TransDate AS DATE),ItemID,TransactionTypeID

答案 1 :(得分:0)

您可以使用带CASE的聚合函数将行转换为列:

SELECT CAST(TransDate AS DATE) AS [TransDate],
  ItemID,
  count(case when TransactionTypeID=20 then TransactionTypeID end) Amt_20,
  count(case when TransactionTypeID=21 then TransactionTypeID end) Amt_21
FROM Transactions
WHERE 
    TransDate BETWEEN '2013-01-01 10:00:00' AND '2013-02-01 10:00:00'
    AND TransactionTypeID IN (20,21)
GROUP BY CAST(TransDate AS DATE),ItemID;

由于您使用的是SQL Server,因此也可以使用PIVOT函数编写:

select TransDate,
  ItemId,
  [20] as Amt_20,
  [21] as Amt_21
FROM
(
  SELECT CAST(TransDate AS DATE) AS [TransDate],
    ItemID,
    TransactionTypeID
  FROM Transactions
  WHERE TransDate BETWEEN '2013-01-01 10:00:00' AND '2013-02-01 10:00:00'
    AND TransactionTypeID IN (20,21)
) d
pivot
(
  count(TransactionTypeID)
  for TransactionTypeID in ([20], [21])
) piv