[英]SQL Select One extra 'false' row per join
我有以下SQL查詢:
SELECT
O.Id AS OrganisationId, o.Name as OrganistionName,
pt.product_type_name as ProductType
FROM
[Content].[Organisations] O (nolock)
JOIN
[Content].[ProductOrganisations] PO (nolock) ON PO.OrganisationId = O.Id
JOIN
[dbo].[report_info] R (nolock) ON PO.ProductId = R.report_id
JOIN
[dbo].[CONTENT_ProductTypes] PT (nolock) ON R.[product_type_id] = PT.PRODUCTTYPEID
WHERE
O.ShowCompanyPage = 1
GROUP BY
O.Id , o.Name, PT.PRODUCTTYPEID, pt.product_type_name
ORDER BY
o.Name, pt.product_type_name
返回以下結果:
OrganisationId OrganistionName ProductType
1 Coca Cola Company Article
1 Coca Cola Company Book
1 Coca Cola Company Company Profile
2 PepsiCo Inc. Audio Conference
2 PepsiCo Inc. Book
2 PepsiCo Inc. Company Profile
3 Pfizer, Inc. Article
3 Pfizer, Inc. Company Profile
3 Pfizer, Inc. Credit Rating Report
但是我需要為每個組織添加額外的“假”行。
該行應作為第一行出現,並且ProductType應為空白。
例如:
OrganisationId OrganistionName ProductType
1 Coca Cola Company
1 Coca Cola Company Article
1 Coca Cola Company Book
1 Coca Cola Company Company Profile
2 PepsiCo Inc.
2 PepsiCo Inc. Audio Conference
2 PepsiCo Inc. Book
2 PepsiCo Inc. Company Profile
3 Pfizer, Inc.
3 Pfizer, Inc. Article
3 Pfizer, Inc. Company Profile
3 Pfizer, Inc. Credit Rating Report
有任何想法嗎?
您可以使用聯合創建此文件:
SELECT O.Id AS OrganisationId, o.Name as OrganistionName, '' as ProductType
FROM [Content].[Organisations] O (nolock)
JOIN [Content].[ProductOrganisations] PO (nolock)
ON PO.OrganisationId = O.Id
JOIN [dbo].[report_info] R (nolock)
ON PO.ProductId = R.report_id
WHERE O.ShowCompanyPage = 1
GROUP BY O.Id , o.Name
union
SELECT DISTINCT O.Id AS OrganisationId, o.Name as OrganistionName, '' as ProductType
FROM [Content].[Organisations] O (nolock)
JOIN [Content].[ProductOrganisations] PO (nolock)
ON PO.OrganisationId = O.Id
JOIN [dbo].[report_info] R (nolock)
ON PO.ProductId = R.report_id
WHERE O.ShowCompanyPage = 1
GROUP BY O.Id , o.Name
ORDER BY o.Name, pt.product_type_name
像這樣用ROLLUP
編寫您的GROUP BY
語句:
GROUP BY O.Id, o.Name, ROLLUP(PT.PRODUCTTYPEID, pt.product_type_name)
類似於上述操作中@JoeMalpass中的注釋中的建議,這是我如何解決的方法。
SELECT DISTINCT O.Id AS OrganisationId, o.Name as OrganisationName, 0, '' as [product_type_name], 0 AS ProductsInType
FROM [Content].[Organisations] O (nolock)
WHERE O.ShowCompanyPage = 1
UNION
SELECT O.Id AS OrganisationId, o.Name as OrganistionName, PT.PRODUCTTYPEID, pt.product_type_name, COUNT(R.report_id) AS ProductsInType
FROM [Content].[Organisations] O (nolock)
JOIN [Content].[ProductOrganisations] PO (nolock)
ON PO.OrganisationId = O.Id
JOIN [dbo].[report_info] R (nolock)
ON PO.ProductId = R.report_id
JOIN .[dbo].[CONTENT_ProductTypes] PT (nolock)
ON R.[product_type_id] = PT.PRODUCTTYPEID
WHERE O.ShowCompanyPage = 1
GROUP BY O.Id , o.Name, PT.PRODUCTTYPEID, pt.product_type_name
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.