2012-02-02 62 views
1

我想使兩個sql語句爲一個。 第一個顯示每天的總訂單,第二個只顯示每天有員工作爲行動文本的訂單的計數。在一個嵌套的SQL查詢中的兩個查詢

select date(dated) date_ord, count(*) as orders_placed 
from stats.sales_actions 
group by date_ord 
order by dated desc 

select date(dated) date_order, count(*) as orders_modified 
from stats.sales_actions 
where action_text LIKE '%STAFF%' 
group by date_ord 
order by dated desc 

如果可能,我想在一個表/ sql查詢中顯示。

+0

歡迎StackOverflow上:如果您發佈的代碼,XML或數據樣本,** **請在高亮文本編輯器的線,然後單擊「代碼示例」按鈕('{ }')在編輯器工具欄上進行恰當的格式化和語法突出顯示! – 2012-02-02 11:34:31

+0

我正在使用MYSQL – rachel 2012-02-02 11:45:39

回答

0
select date(dated) date_ord, 
count(*) as orders_placed, 
SUM (
     CASE 
      WHEN action_text LIKE '%STAFF%' 
      THEN 1 ELSE 0 END) AS ORDERS_STAFF 
from stats.sales_actions 
group by date_ord 
order by dated desc 

這顯示一排兩個值。如果你喜歡2行,只需在查詢之間使用聯合。

+0

如果你發佈代碼,XML或數據樣本,**請在文本編輯器中突出顯示這些行,然後單擊「代碼示例」按鈕(「{}」)在編輯器工具欄上進行恰當的格式化和語法突出顯示! – 2012-02-02 11:39:44

+0

對不起,我覺得現在好了。 – chris 2012-02-02 11:45:28

+0

謝謝它工作..!祝你有美好的一天 – rachel 2012-02-02 11:49:45

2

只需使用UNION

select date(dated) date_ord, count(*), 'orders_places' as orders_placed 
from stats.sales_actions 
group by date_ord 
order by dated desc 
UNION 
select date(dated) date_order, count(*), 'orders_modified' as orders_modified 
from stats.sales_actions 
where action_text LIKE '%STAFF%' 
group by date_ord 
order by dated desc 
+0

聯合的一個問題是他們不會知道哪些項目是orders_placed或orders_modified,因爲它將具有相同的列名稱。你將不得不包括一些東西來區分它們。 – Taryn 2012-02-02 11:38:52

+0

@bluefeet你可以添加像我現在陳述的另一列。 – 2012-02-02 11:39:17

+3

簡單有效的解決方案 – Taryn 2012-02-02 11:41:45

1

您可以使用UNION來實現此目的 - 然後您可以使用AS關鍵字爲count colums命名,以便將它們區分開來。例如:

select date(dated) date_ord, count(*) AS placed, 'orders_places' as orders_placed 
from stats.sales_actions 
group by date_ord 
order by dated desc 
UNION 
select date(dated) date_order, count(*) AS modified, orders_modified' as orders_modified 
from stats.sales_actions 
where action_text LIKE '%STAFF%' 
group by date_ord 
order by dated desc 
+0

你可以解釋一下這個 – rachel 2012-02-02 11:46:38

+0

當然,它實際上是一個非常簡單的變化,從你有兩個查詢。我剛剛複製並粘貼了你的查詢,把UNION(本質上把這兩個查詢合併到一個結果表中)將它們中的兩個分組,然後命名你的count(*)列,因爲如果我沒有它們會分享相同的名字。您可以使用AS關鍵字 - [[column_to_select] AS名稱]來執行此操作 - 這會在結果中爲列名稱「column_to_select」指定名稱「name」。 – Hecksa 2012-02-03 09:09:14

+0

好的,謝謝@hecksa – rachel 2012-02-03 09:44:08

1
select date_ord, sum(orders_placed) as orders_placed , 
      sum(orders_modified) as orders_modified 
    from( 

      select date(dated) date_ord, count(*) as orders_placed , 0 as orders_modified 
      from stats.sales_actions 
      group by date_ord 
      order by dated desc 

      UNION 

      select date(dated) date_ord, 0 as orders_placed, count(*) as orders_modified 
      from stats.sales_actions 
      where action_text LIKE '%STAFF%' 
      group by date_ord 
      order by dated desc 
     ) temp 
      group by date_ord 
      order by dated desc 
+0

做一些這樣的事情 – Santosh 2012-02-02 12:00:59