我需要帮助编写一个SQL语句,该语句将从两个不同的表创建一个SQL视图,从每个可能性中捕获2条记录。
例如,如果customer表中有三条记录与GROUP A
的{{1}}和STATE
匹配,那么您应该只显示视图中3条记录中的2条记录 - 但是如果如果客户位于NV
和GROUP A
STATE
或PA
和GROUP B
,则还需要在视图中捕获这些附加记录。
我是SQL新手。我的想法都没有奏效,所以我感谢任何有助于我解决问题的反馈。以下查询是我设法写的:
STATE of NV
以下是它产生的观点:
SELECT customer_table.Customer_ID,
customer_table.First_Name,
customer_table.Last_Name,
customer_table.Email_Address,
customer_table.STATE,
customer_table.GROUP_,
customer_table.Timestamp_,
product_table.Prod_Name,
product_table.Prod_desc
FROM customer_table
INNER JOIN product_table ON customer_table.Customer_ID = product_table.Customer_ID
ORDER BY customer_table.STATE,
customer_table.GROUP_;
答案 0 :(得分:2)
我相信你最好的选择是UNION查询。这会将两个单独的SELECT
语句的结果叠加在一起。此外,您可以使用WHERE
子句过滤这两个查询。第二个将有点棘手,因为你有两个条件,所以我们将使用OR
来分隔它们。
/* First SELECT finds two records in Nevada for Group A*/
SELECT TOP 2
customer_table.Customer_ID,
customer_table.First_Name,
customer_table.Last_Name,
customer_table.Email_Address,
customer_table.STATE,
customer_table.GROUP_,
customer_table.Timestamp_,
product_table.Prod_Name,
product_table.Prod_desc
FROM customer_table
INNER JOIN product_table ON customer_table.Customer_ID = product_table.Customer_ID
WHERE customer_Table.GROUP_ = 'A' AND customer_table.STATE = 'NV'
/*UNION ALL will stack the results of these two queries into a single result set*/
UNION ALL
/*Second SELECT finds all records for PA, GROUP A and NV, GROUP B*/
SELECT
customer_table.Customer_ID,
customer_table.First_Name,
customer_table.Last_Name,
customer_table.Email_Address,
customer_table.STATE,
customer_table.GROUP_,
customer_table.Timestamp_,
product_table.Prod_Name,
product_table.Prod_desc
FROM customer_table
INNER JOIN product_table ON customer_table.Customer_ID = product_table.Customer_ID
WHERE (customer_table.GROUP_ = 'A' AND customer_Table.STATE = 'PA') OR
(customer_table.GROUP_ = 'B' AND customer_table.STATE = 'NV')
最后,TOP 2
是SQL Server语法,如果这是MYSQL
,则说“仅返回此结果集的前两个记录”,然后取出TOP 2
并粘贴{{ 1}}在LIMIT 2
语句的末尾代替。