簡體   English   中英

SQL Server:查詢多個表以創建預格式化的“模板” csv,以導出到Excel

[英]SQL Server: query multiple tables to create a pre-formated “template” csv for export into Excel

我正在嘗試創建完成以下任務所需的SQL。 順便說一句,我針對托管的SQL Server數據庫使用服務器端Report Builder,因此我只能做些事情。 有3張桌子。 銷售員表(銷售),項目表(項目)和交易表(tx)。

這是一個例子:

銷售人員表(銷售)

Person A
Person B

項目ID表(項目)

  10   
  20
  30
 100
 200
 300
1000
2000
3000

交易表(TX)

100 (person A)
300 (person B)
300 (person A)
200 (person B)

報表生成器中的所需結果:

Person A
Item 100: 1
Item 200: 0 (NULL)
Item 300: 1

-- NEW PAGE --

Person B:
Item 100: 0 (NULL)
Item 200: 1
Item 300: 1

我的問題:這是我想出的SQL。 我需要能夠生成一致的結果集,而不管某個銷售人員是否出售了某件商品,以便更輕松地導入Excel。 另外,我只查找代碼在100到300之間且在指定日期范圍內的項目。 我的SQL忽略了日期范圍和項目代碼范圍。 我最初在WHERE子句中具有這些指令,但它僅返回兩個表中的那些行,並且丟失了任何值為null的itemcode(充當INNER連接)的占位符。 在報表制作工具中,我將統計銷售員售出的每種商品的數量。

SELECT  
    tx.date, sales.salesperson, items.itemcode
FROM 
    tx
LEFT OUTER JOIN 
    itemcode ON (tx.itemcode = items.itemcode) 
             AND (date BETWEEN "10/1/2017" AND "12/31/2017") 
             AND (itemcode BETWEEN "100" AND "300")
INNER JOIN 
    sales ON (tx.salesID = sales.salesID)
ORDER BY 
    itemcode ASC

非常感謝您對我的挑戰的任何見解!

如果您需要所有銷售人員和所有項目,則可以使用cross join生成行。 您可以使用left joinexists來引入可用數據:

select s.person, i.itemcode,
       (case when exists (select 1
                          from tx
                          where tx.salesid = s.salesid and tx.itemcode = i.itemcode
                         )
             then 1 else 0
        end) as has_sold
from sales s cross join
     items i 
where i.itemcode between 100 and 300
order by s.saledid, i.itemcode;

如果要計數,請使用left joingroup by

select s.person, i.itemcode, count(tx.salesid) as num_sold
from sales s cross join
     items i left join
     tx
     on tx.salesid = s.salesid and tx.itemcode = i.itemcode
where i.itemcode between 100 and 300
order by s.saledid, i.itemcode;

這是一個使用cross join (獲取銷售和商品的所有組合)和left join (獲取給定日期的交易)的示例

SELECT  
    tx.date, sales.salesperson, items.itemcode
FROM 
    Items
CROSS JOIN 
    sales
LEFT OUTER JOIN 
     tx ON (items.itemcode = tx.itemcode) 
     AND date BETWEEN '10/1/2017' AND '12/31/2017'
     AND (tx.salesID = sales.salesID)
WHERE
    (items.itemcode BETWEEN '100' AND '300')
ORDER BY 
    itemcode ASC

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM