6

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

前::

[日期] [ID] [AMT] [类型]
2013-01-11 36374DCD-47FE-48D8-8E70-8D3B37385311 2 20
2013-01-11 36374DCD-47FE-48D8-8E70-8D3B37385311 10 21
2013-01-11 44​​34E2D5-1D08-45FA-AADF-F653BF9A0D97 4 20
2013-01-11 44​​34E2D5-1D08-45FA-AADF-F653BF9A0D97 4 21

后::

[日期] [ID] [AMT 20] [AMT 21]
2013-01-11 36374DCD-47FE-48D8-8E70-8D3B37385311 2 10
2013-01-11 44​​34E2D5-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

任何帮助表示赞赏,谢谢!

4

2 回答 2

3

您可以使用带有 a 的聚合函数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
于 2013-05-01T23:41:06.167 回答
1

bluefeet answer 可能是最好的方法,但是如果您的查询变得更复杂,您可以随时根据需要使用尽可能多的 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
于 2013-05-01T23:45:09.650 回答