Sql客户用所有产品查询

时间:2017-03-02 14:43:33

标签: c# sql sql-server

我有3张桌子

  • 客户(cid,姓名,地址)
  • 报纸(nid,名称,价格)
  • Weeklymag(wid,名称,价格)
  • 订单(id,cid,nid,wid)

现在一位顾客有两份以上的报纸或杂志。 我正在寻找以下结果的查询

john--news1,news2,weeklymag1

King--news1

Jessel--news2,mag1,weeklymag2

Smith--new4,mag3

或者我是否需要创建此报告的程序?

感谢您的时间和答案。

3 个答案:

答案 0 :(得分:0)

您可以使用GROUP CONCAT执行此操作:

> 1.0 = 1.0;
poly: : error: Type error in function application.
   Function: = : ''a * ''a -> bool
   Argument: (1.0, 1.0) : real * real
   Reason: Can't unify ''a to real (Requires equality type)

答案 1 :(得分:0)

使用GROUP_CONCAT FUNCTION

SELECT c.name, CONCAT(GROUP_CONCAT(n.name SEPARATOR ','), IF(COUNT(DISTINCT n.id)>0 AND COUNT(DISTINCT m.id) >0,',',''), GROUP_CONCAT(m.name SEPARATOR ',')) mags
FROM customers c
LEFT JOIN orders o ON o.cid = c.cid
LEFT JOIN newspaper n ON n.nid = o.nid
LEFT JOIN weeklymag m ON m.wid = o.wid
GROUP BY c.cid

答案 2 :(得分:0)

SELECT C.NAME,

    STUFF((SELECT DISTINCT' '+ N.NAME + ' | '
                FROM NEWSPAPER N   
                JOIN ORDERS O ON O.NEWS_ID = N.ID 
                WHERE O.CUST_ID = C.ID
                FOR XML PATH('') , TYPE).value('.','NVARCHAR(MAX)'),1,0,'')as NEWS
     ,
     STUFF((SELECT DISTINCT' '+ w.name +' | '
                FROM weekly w   
                JOIN ORDERS O ON O.Weekly_id = w.id  
                WHERE O.CUST_ID = C.ID
                FOR XML PATH('') , TYPE).value('.','NVARCHAR(MAX)'),1,0,'')as WEEKLY
    ,STUFF((SELECT DISTINCT' '+ m.name +' | '
                FROM monthly m   
                JOIN ORDERS O ON o.monthly_id  = m.id  
                WHERE O.CUST_ID = C.ID
                FOR XML PATH('') , TYPE).value('.','NVARCHAR(MAX)'),1,0,'')as MAG

FROM CUSTOMER C