SQL如何根据条件选择列

时间:2017-11-23 05:07:22

标签: sql

我正在创建一个存储过程来选择客户详细信息。但是每个客户的报告都有不同的要求。

例如, 我有两张相同设计的桌子。一个是细节,另一个只是一个指标。

tbl_Cust_Details
------------------------------
|Customer|Address|Contact|Qty|
|--------+-------+-------+---|
|ABC123  |NYC    |989123 |23 |
|ABD222  |WDC    |549585 |54 |
------------------------------

tbl_Column_Indicator
------------------------------
|Customer|Address|Contact|Qty|
|--------+-------+-------+---|
|ABC123  |1      |0      |1  |
|ABD222  |1      |1      |0  |
------------------------------

如何根据每个客户的tbl_Cust_Details指标从tbl_Column_Indicator中选择列。

1=show
0=hide

期望的输出:

For customer ABC123:
----------------------
|Customer|Address|Qty|
|--------+-------+---|
|ABC123  |NYC    |23 |
----------------------

For customer ABD222:
--------------------------
|Customer|Address|Contact|
|--------+-------+-------|
|ABD222  |WDC    |549585 |
--------------------------

请帮忙。谢谢。

2 个答案:

答案 0 :(得分:0)

只需使用简单的case表达式

即可
SELECT 
          D.Customer,
          CASE(I.Address) WHEN 1 THEN D.Address ELSE NULL END [Address],
          CASE(I.Contact) WHEN 1 THEN D.Contact ELSE NULL END [Contact],
          CASE(I.Qty) WHEN 1 THEN D.Qty ELSE NULL END [Qty]
          FROM tbl_Cust_Details D
JOIN tbl_Column_Indicator I ON I.Customer = D.Customer

结果:

Customer    Address Contact Qty
ABC123      NYC     NULL    23
ABD222      WDC     549585  NULL

答案 1 :(得分:0)

您可以使用动态sql

DECLARE @Customer VARCHAR(20) ='ABC123'

DECLARE @SqlColumns NVARCHAR(MAX) ='[Customer]'
SELECT TOP 1 @SqlColumns = @SqlColumns +
    CASE WHEN Address = 1 THEN ', [Address]' ELSE '' END +
    CASE WHEN Contact = 1 THEN ', [Contact]' ELSE '' END +
    CASE WHEN Qty = 1 THEN ', [Qty]' ELSE '' END 
FROM tbl_Column_Indicator WHERE Customer = @Customer

DECLARE @SqlText NVARCHAR(MAX) = 'SELECT ' + @SqlColumns + ' FROM tbl_Cust_Details WHERE Customer =''' + @Customer + ''''

EXEC (@SqlText)

客户' ABC123'

的结果
Customer   Address    Qty
---------- ---------- -----------
ABC123     NYC        23

对于客户' ABD222'

Customer   Address    Contact
---------- ---------- -----------
ABD222     WDC        549585