2016-11-28 90 views
0

因此,我有一張表用於一個企業的所有交易,非常簡單,它有一個支付方法列,列出所有交易如何進行,現金,信用或借記。單個SQL查詢中的多個計數(交易類型)

我想要做的是創建與查詢兩列,計算出每個交易是如何完成的,一列是現金,另一個是卡,其中包括所有的信用卡和借記卡購買。

這是我到目前爲止有:

SELECT COUNT (*) as CashTransactions 
FROM Transaction 
WHERE PaymentMethod='Cash' 

而我所要的輸出是爲

Cash Transactions |  Card Transactions 

(Count of Cash) | (Count of Credit AND Debit) 
+0

好問題。一個更好的問題是顯示你在發佈之前已經研究過你的問題的事實。看看[在問你之前](http://www.catb.org/~esr/faqs/smart-questions.html#before)。你是否搜索過Stackoverflow?網絡怎麼樣?爲什麼你沒有發現解決你的問題?顯示你在你的問題中研究的內容。 – MikeJRamsey56

回答

0

夫婦選擇這裏。我強烈建議選項一,它更乾淨,更快。

選項1

SELECT PaymentMethod, COUNT(*) AS NumberOfTransactions 
FROM Transaction 
GROUP BY PaymentMethod 

在所得:

PaymentMethod | NumberOfTransactions 
------------------------------------ 
Cash   | 33 
Credit  | 12 
Debit   | 87 

或者選項2

SELECT (
SELECT COUNT(*) AS NumberOfTransactions 
FROM Transaction 
WHERE PaymentMethod = 'Cash' 
) as CashTransactions, 
(
SELECT COUNT(*) AS NumberOfTransactions 
FROM Transaction 
WHERE NOT PaymentMethod = 'Cash' 
) as OtherTransactions 

從而造成:

CashTransactions| OtherTransactions 
------------------------------------ 
33    | 99 
+0

thx bb,就像一個魅力。有沒有簡單的方法來製作百分比/頻率欄?或者是否會涉及大量的子查詢? – NickA

0

只是總結,而不是計數:

SELECT 
    ABS(SUM(PaymentMethod = 'Cash')) AS CashTransactions, 
    ABS(SUM(PaymentMethod <> 'Cash')) AS CardTransactions 
FROM 
    Transaction 
0

如果使用SQL Server,你可以試試這個查詢:

SELECT 
    SUM(CASE WHEN PaymentMethod='Cash' THEN 1 ELSE 0 END) as CashTransaction, 
    SUM(CASE WHEN PaymentMethod IN ('Credit','Debit') THEN 1 ELSE 0 END) as CardTransaction 
FROM Transaction 

但是,如果你使用MS-訪問,查詢,你可以試試這個查詢:

SELECT sum(IIF(PaymentMethod='Cash',1,0)) as CashTransaction, sum(IIF(PaymentMethod in ('Credit','Debit'),1,0)) as CardTransaction 
FROM Transaction;